每次继承/扩展类时,都会在超类对象中创建超类成员的副本,因此可以使用子类对象访问这两个类的成员。
样品
在以下示例中,有一个名为SuperClass的类。 这个类的名字是demo ()。 我们在另一个类(SubClass )中继承了那个类。
然后创建子类对象并调用方法demo ()。 类super class {
公共void demo () {
system.out.println(demomethod );
}
}
publicclassubclassextendssuperclass {
publicstaticvoidmain (string args [ ] ) {
SubClassobj=newSubClass (;
obj.demo (;
}
}
输出结果demomethod
继承中国超类构造函数
继承不会继承构造函数。 必须使用super关键字显式调用。
如果超类具有参数化构造函数。 您必须在子类的构造函数中接受这些参数。 在子类的构造函数中,使用super ()调用超类的构造函数publicstudent(stringname,intage,Stringbranch,intStudent_id )
super(name,age );
this.branch=branch;
this.Student_id=Student_id;
}
样品
以下java程序说明如何使用super关键字从子类构造函数中调用超类构造函数。 类人员{
公共字符串名称;
公共信息;
公共人员(string name,intage ) {
this.name=name;
this.age=age;
}
publicvoiddisplayPerson (
system.out.println (dataofthepersonclass : );
system.out.println (' name : ' this.name );
system.out.println(age: ) this.age );
}
}
publicclassstudentextendsperson {
公共字符串分支;
publicintStudent_id;
公共student (string name,intage,Stringbranch,intStudent_id ) {
super(name,age );
this.branch=branch;
this.Student_id=Student_id;
}
publicvoiddisplayStudent (
system.out.println('Person类的数据:');
system.out.println (' name : ' this.name );
system.out.println(age: ) this.age );
system.out.println (' branch : ' this.branch );
system.out.println (student id : ) this.student_id );
}
publicstaticvoidmain (string [ ] args ) throwsclonenotsupportedexception {
person person=new student (' Krishna ',20,' IT ',1256 );
person.displayPerson (;
}
}
输出结果Person类的数据:
Name:Krishna
Age:20