在Java的多态特点中,子类继承父类的成员变量(member variable)时,如果字面值(variable literal)不一致时。不是说子类没有继承父类的特性,而是子类将父类的特性覆盖(override)了。这时将会使用子类的成员变量,而父类的成员变量将被保护起来。如果想要使用父类的成员变量,则可以改变其布雷变量的修饰符。
下面将举一个小例子:
//定义一个父类Fruit
public class Fruit {
String color="yellow";
String size="small";
//定义两个Default方法
String getFruitColor(){
return color;
}
String getFruitSize(){
return size;
}
}
//定义一个子类Apple
public class Apple extends Fruit {
String apple_color="green";
String apple_size="big";
String getFruitColor(){
return apple_color;
}
String getFruitSize(){
return apple_size;
}
public static void main(String[] args) {
Fruit f=new Apple();//创建一个Fruit类的Apple对象
System.out.println(f.getFruitColor());
System.out.println(f.getFruitSize());
}
}
此时输出的结果为:
green
big
Process finished with exit code 0
以上的例子中,我们创建的Fruit类的Apple对象完全的覆盖了其父类的变量和方法。那我们如何不让子类覆盖呢,其实只需要在不想被覆盖的变量和方法前加上关键字static就可以了,因为加上static关键字下的变量和方法属于类,不随着对象而创建副本。例如:
public class Fruit {
static String color="yellow";
String size="small";
//定义一个静态方法
static String getFruitColor(){
return color;
}
//定义一个Default方法
String getFruitSize(){
return size;
}
}
//定义一个子类Apple
public class Apple extends Fruit {
static String apple_color="green";
String apple_size="big";
//定义一个静态方法
static String getFruitColor(){
return apple_color;
}
//定义一个Default方法
String getFruitSize(){
return apple_size;
}
public static void main(String[] args) {
Fruit f=new Apple();//创建一个Fruit类的Apple对象
System.out.println(f.getFruitColor());
System.out.println(f.getFruitSize());
}
}
此时输出的结果为:
yellow
big
Process finished with exit code 0