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 Sample("Krishna", 20, "IT", 1256);
//Converting super class variable to sub class type
Sample obj = (Sample) person;
obj.displayPerson();
obj.displayStudent();
}
} 出力
Data of the Person class: Name: Krishna Age: 20 Data of the Student class: Name: Krishna Age: 20 Branch: IT Student ID: 1256
例
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 sup = new Test();
//Converting super class variable to sub class type
Test obj = (Test) sup;
obj.superMethod();
obj.subMethod();
}
} 出力
Constructor of the super class Constructor of the sub class Method of the super class Method of the sub 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