一 .成员变量的继承与隐藏
父类创建子类时,子类可以继承父类的成员变量和成员方法。子类在使用父类的同名变量时,父类中的同名变量就会被隐藏。
代码如下:
class Wc {
String name;
int age;
public Wc(String name,int age) { //有参构造
this.name = name;
this.age = age;
}
public Wc( ) { //无参构造
this.name = "name";
this.age = 17;
}
public void Wg( ) { //显示父类中的成员变量
System.out.println("WC "+"Name: "+this.name+"; age: "+this.age);
}
}
class Nh extends Wc {
String name;
int ID; //声明新的成员变量
public Nh( ){
this.name = "Nh name";
this.age = 20;
}
public Nh(String name,int age,int ID) {
this.name = name;
this.age = age;
this.ID = ID;
}
public void Zj( ) { //子类中的成员变量
System.out.println("Nh "+"Name: "+this.name+"; age: "+this.age+"; ID:"+this.ID);
}
}
public class Giao {
public static void main(String[ ] args){
Nh tt1 =new Nh( ); //调用无参构造方法创建对象
Nh tt2 =new Nh("NB",22,2022); //调用有参构造方法
tt1.Wg();
tt2.Wg(); //调用父类的成员方法
tt1.Zj();
tt2.Zj();//调用子类的成员方法
}
}
注释:子类成员变量ID未被显式赋值,所以系统自动为其初始化为默认值0。
二.方法的继承与覆盖
子类中如果重新定义了从父类继承来的方法,则父类的这个方法在子类中会不存在,我们将情况简称方法覆盖。
代码如下:
class Fl { //声明父类
void Nb( ){//声明成员方法
this.En();
this.Dd(0);
}
void En( ) {//声明同类,同名,同参数成员方法
System.out.println("父类:同类型,同名,同参数成员方法。");
}
void Dd(int a) {//声明同类型,同名但参数不同的成员方法
System.out.println("父类:同类型,同名但参数不同的成员方法。");
}
}
class Zl extends Fl {
void Nl( ){
this.Xh( );
this.Aj( );
}
void Xh( ) {
System.out.println("子类:同类型,同名,同参数成员方法。");
}
void Aj( ) {
System.out.println("子类:同类型,同名但参数不同的成员方法。");
}
}
public class Example {
public static void main(String[ ] args) {
Zl tt = new Zl( );
tt.Nb();//调用父类的成员方法
tt.Nl();//调用子类的成员方法w
}
}
注释:要使子类的方法完全覆盖父类中的方法,方法类型,名称和参数必须完全一致,否则,任何一项不同均不能覆盖。