如何在Java中将子类变量转换为超类类型?
继承 是两个类之间的关系,其中一个类继承另一个类的属性。可以使用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("Person类的数据: ");
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("学生班数据: ");
System.out.println("Name: "+super.name);
System.out.println("Age: "+super.age);
System.out.println("Branch: "+this.branch);
System.out.println("学生卡: "+this.Student_id);
}
public static void main(String[] args) {
Person person = new Person("Krishna", 20);
//将超类变量转换为子类类型
Sample sample = new Sample("Krishna", 20, "IT", 1256);
person = sample;
person.displayPerson();
}
}输出结果Person类的数据: Name: Krishna Age: 20
示例
class Super{
public Super(){
System.out.println("Constructor of the Super class");
}
public void superMethod() {
System.out.println("超类的方法 ");
}
}
public class Test extends Super {
public Test(){
System.out.println("Constructor of the sub class");
}
public void subMethod() {
System.out.println("子类的方法 ");
}
public static void main(String[] args) {
Super obj = new Test();
obj.superMethod();
}
}输出结果Constructor of the Super class Constructor of the sub class 超类的方法
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短