当子类与父类中存在同名的成员变量时子类中会隐藏父类中的同名成员变量。
什么是向上转型?
将子类的对象赋给父类的对象,这种操作我们称之为向上转型。(个人理解)
public class SuperClass{}
public class SubClass extends SuperClass{}
SuperClass superClass = null;
superClass = new SubClass();
向上转型后我们将不能操作子类新增的成员变量和子类新增的方法,可以操作子类继承或重写的方法和子类继承或隐藏的成员变量
demo
/**
* Created by liuquan on 2020/3/28.
*/
public class SuperClass {
static int age = 10;
String name = "super";
String getInfo(){
return "super";
}
String getCurrentName(){
return this.name;
}
}
public class SubClass extends SuperClass{
static int age = 20;
String name = "sub";
String addr = "湖北";
String getInfo(){
return "sub";
}
String getUserName(){
return "userName";
}
String getCurrentName(){
return this.name;
}
}
/**
* Created by liuquan on 2020/3/28.
*/
public class TestTypeConversion {
public static void main(String[] args){
SubClass subClass = new SubClass();
System.out.println("subClass.getInfo():"+subClass.getInfo());
System.out.println("subClass.getCurrentName():"+subClass.getCurrentName());
System.out.println("subClass.getUserName():"+subClass.getUserName());
System.out.println("subClass.name:"+subClass.name);
System.out.println("subClass.age:"+subClass.age);
System.out.println("subClass.addr:"+subClass.addr);
System.out.println("");
SuperClass superClass = new SubClass();
System.out.println("superClass.getInfo():"+superClass.getInfo());
System.out.println("superClass.getCurrentName():"+superClass.getCurrentName());
System.out.println("superClass.name:"+superClass.name);
System.out.println("superClass.age:"+superClass.age);
//System.out.println("superClass.age:"+superClass.getUserName());//cannot resolve method 'getUsername()'
//System.out.println("superClass.addr:"+superClass.addr);//cannot resolve symbol 'addr'
}
}