继承以及向上转型
继承的大致思路
先编写一个共有属性的一般类,根据该一般类在编写具有特殊属性的新类,新类继承一般类的状态和行为,并根据需要增加它自身的新的状态和行为。其中由继承而得到的类称为子类,被继承的类称为父类(超类)。
声明一个类的子类的格式如下:
class 子类名 extends 父类名{……}
子类中从父类继承而来的成员变量的隐藏
在编写子类时,我们仍然可以声明成员变量,一种特殊的情况是,如果所声明的成员变量的名字和从父类继承来的成员变量的名字相同(声明的类型可以不同),在这种情况下,子类就会隐藏掉所继承的成员变量,即子类重新定义了这个成员变量。需要注意的是,子类对象仍然可以调用方法,在所调方法中通过super关键字操作隐藏的成员变量。
子类中从父类继承而来的方法的隐藏
子类可以通过重写方法的方法来隐藏继承而来的方法。需要注意的是,子类对象仍然可以调用方法,在所调方法中通过super关键字操作隐藏的方法。
对象的上转型对象
假设,A类是B类的父类,当用子类创建一个对象,并把这个对象的引用放到父类的对象中时,此时这个父类的对象就称为子类创建的上转型对象
对象的上转型对象的变化
package com.kiki;
/*
* Person类
*/
public class Person {
String country = "country is undefined.";
String language = "language is unkown.";
void printCountry() {
System.out.println("Person类中的country为:"+country);
}
void printLanguage() {
System.out.println("Person类中的language为:"+language);
}
}
package com.kiki;
/*
* Chinese类隐藏了Person类country成员变量,并重写了Person类中的printCountry方法
*/
public class Chinese extends Person {
int country = 1;
@Override
void printCountry() {
System.out.println("使用super关键字访问父类中的printCountry方法变量");
super.printCountry();//用super关键字访问Person的printCountry方法
System.out.println("Chinese类中的country为:"+country);
}
void print() {
System.out.println("使用super关键字访问父类中的country变量为:"+super.country);//用super关键字访问Person的country成员变量
}
}
package com.kiki;
public class Demo25 {
public static void main(String[] args) {
Chinese lisi = new Chinese();
lisi.printCountry();
lisi.print();
lisi.printLanguage();
System.out.println(lisi.country);
System.out.println(lisi.language);
System.out.println("*****************");
System.out.println("");
Person person = lisi;//这里是向上转型,person是上转型对象,向上转型都会成功,即是安全的
person.printCountry();//向上转型对象访问重写的方法量
person.printLanguage();//向上转型对象访问继承的方法
System.out.println(person.country);//向上转型对象访问隐藏的成员变量
System.out.println(person.language);//向上转型对象访问继承的成员变量
System.out.println("*****************");
System.out.println("");
lisi = (Chinese) person;//这里是向下转型,此处是安全的
lisi.printCountry();
lisi.printLanguage();
System.out.println(lisi.country);
System.out.println(lisi.language);
}
}
运行结果:
使用super关键字访问父类中的printCountry方法变量
Person类中的country为:country is undefined.
Chinese类中的country为:1
使用super关键字访问父类中的country变量为:country is undefined.
Person类中的language为:language is unkown.
1
language is unkown.
*****************
使用super关键字访问父类中的printCountry方法变量
Person类中的country为:country is undefined.
Chinese类中的country为:1
Person类中的language为:language is unkown.
country is undefined.
language is unkown.
*****************
使用super关键字访问父类中的printCountry方法变量
Person类中的country为:country is undefined.
Chinese类中的country为:1
Person类中的language为:language is unkown.
1
language is unkown.