Javaでサブクラス変数をスーパークラス型に変換するにはどうすればよいですか?
継承 1つのクラスが他のクラスのプロパティを継承する2つのクラス間の関係です。この関係は、extendsキーワードを使用して-
として定義できます。public class A extends B{
}
プロパティを継承するクラスはサブクラスまたは子クラスと呼ばれ、プロパティを継承するクラスはスーパークラスまたは親クラスです。
継承では、スーパークラスメンバーのコピーがサブクラスオブジェクトに作成されます。したがって、サブクラスオブジェクトを使用すると、両方のクラスのメンバーにアクセスできます。
サブクラス変数をスーパークラスタイプに変換する
サブクラス変数(値)をスーパー変数に直接割り当てることができます。つまり、スーパークラス参照変数はサブクラスオブジェクトを保持できます。ただし、この参照を使用すると、スーパークラスのメンバーにのみアクセスできます。サブクラスのメンバーにアクセスしようとすると、コンパイル時エラーが生成されます。
例
class Person{
public String name;
public int age;
public Person(String name, int age){
this.name = name;
this.age = age;
}
public void displayPerson() {
System.out.println("Data of the Person class: ");
System.out.println("Name: "+this.name);
System.out.println("Age: "+this.age);
}
}
public class Sample extends Person {
public String branch;
public int Student_id;
public Sample(String name, int age, String branch, int Student_id){
super(name, age);
this.branch = branch;
this.Student_id = Student_id;
}
public void displayStudent() {
System.out.println("Data of the Student class: ");
System.out.println("Name: "+super.name);
System.out.println("Age: "+super.age);
System.out.println("Branch: "+this.branch);
System.out.println("Student ID: "+this.Student_id);
}
public static void main(String[] args) {
Person person = new Person("Krishna", 20);
//Converting super class variable to sub class type
Sample sample = new Sample("Krishna", 20, "IT", 1256);
person = sample;
person.displayPerson();
}
} 出力
Data of the Person class: Name: Krishna Age: 20
例
class Super{
public Super(){
System.out.println("Constructor of the Super class");
}
public void superMethod() {
System.out.println("Method of the super class ");
}
}
public class Test extends Super {
public Test(){
System.out.println("Constructor of the sub class");
}
public void subMethod() {
System.out.println("Method of the sub class ");
}
public static void main(String[] args) {
Super obj = new Test();
obj.superMethod();
}
} 出力
Constructor of the Super class Constructor of the sub class Method of the super class
-
formatメソッドを使用してdouble値をJava文字列に変換するにはどうすればよいですか?
このメソッドは、フォーマットStringと引数(varargs)を受け入れ、指定された変数のStringオブジェクトを指定されたフォーマットで返します。 format()メソッドを使用して、double値を文字列にフォーマットできます。それに“%f”を渡します フォーマット文字列として(必要なdouble値とともに) 例 import java.util.Scanner; public class ConversionOfDouble { public static void main(String args[]) { Sc
-
Javaを使用してプリミティブデータをラッパークラスに変換するにはどうすればよいですか?
Javaは、java.langパッケージでラッパークラスと呼ばれる特定のクラスを提供します。これらのクラスのオブジェクトは、それらの中にプリミティブデータ型をラップします。 ラッパークラスを使用すると、ArrayList、HashMapなどのさまざまなCollectionオブジェクトにプリミティブデータ型を追加することもできます。ラッパークラスを使用して、ネットワーク経由でプリミティブ値を渡すこともできます。 例 import java.util.Scanner; public class WrapperExample { public static void ma