Java super keyword: Super calls the constructor of the parent class and uses super to access the members of the parent class
•
Java
Use super to call the constructor of the parent class
super(parameter-list);
public People(String name,int age,String sex,String sn) { this.name=name; this.age=age; this.sex=sex; this.sn=sn; } public People(String name,String sn) { this.name=name; this.sn=sn; }
public Student(String name,String sn,String stuno,String department) { super(name,age,sex,sn); //调用父类中含有4个参数的构造方法 this.stuNo=stuno; this.department=department; } public Student(String name,String stuNo) { super(name,sn); //调用父类中含有两个参数的构造方法 this.stuNo=stuNo; }
Using super to access parent class members
super.member
Example 1
//父类Animal的定义 public class Animal { public String name; //动物名字 } //子类Cat的定义 public class Cat extends Animal { private String name; //名字 public Cat(String aname,String dname) { super.name=aname; //通过super关键字来访问父类中的name属性 this.name=dname; //通过this关键字来访问本类中的name属性 } public String toString() { return"我是"+super.name+",我的名字叫"+this.name; } public static void main(String[] args) { Animal cat=new Cat("动物","喵星人"); System.out.println(cat); } }
我是动物,我的名字叫喵星人
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码