Java中,使用关键词extends,可以使继承类拥有基类的属性和方法,前提条件是基类的属性和方法是public或protected。在此讨论一个特殊情况,如果继承类、基类的属性和方法一样怎么办?
案例一:属性、方法均继承
class Person {
private String name = "Person";
public void getName() {
System.out.println("Class name is :" + this.getClass().getSimpleName() + " ---- property name is :" + name);
}
}
public class Student extends Person{
public static void main(String[] args) {
Person person = new Person();
person.getName();
Student student = new Student();
student.getName();//继承类继承了基类的方法
Person normalStudent = new Student();
normalStudent.getName();//动态编译,基类引用调用继承类方法
}
}
/**
* OUTPUT
* Class name is :Person ---- property name is :Person
* Class name is :Student ---- property name is :Person
* Class name is :Student ---- property name is :Person
*/
案例二、属性名称相同、方法继承基类
class Person {
private String name = "Person";
public void getName() {
System.out.println("Class name is :" + this.getClass().getSimpleName() + " ---- property name is :" + name);
}
}
public class Student extends Person{
private String name = "Student";
public static void main(String[] args) {
Person person = new Person();
person.getName();
Student student = new Student();
student.getName();//继承类继承了基类的方法
Person normalStudent = new Student();
normalStudent.getName();//动态编译,基类引用调用继承类方法
}
}
/**
* OUTPUT
* Class name is :Person ---- property name is :Person
* Class name is :Student ---- property name is :Person
* Class name is :Student ---- property name is :Person
*/
对比案例一、案例二发现,属性名称相同没产生任何变化。继承类的属性被隐藏,通过继承获取的方法,始终只会对基类的属性进行操作。Java中属性不支持重写。道理也很合理,如果连属性都能重写,就违背了封装、安全的初衷。如果继承类的方法会更改属性值,本来是打算更改基类属性,结果却更改了继承类属性,就乱了。
案例三、方法重写、属性名称相同
class Person {
private String name = "Person";
public void getName() {
System.out.println("Class name is :" + this.getClass().getSimpleName() + " ---- property name is :" + name);
}
}
public class Student extends Person{
private String name = "Student";
public void getName() {
System.out.println("Class name is :" + this.getClass().getSimpleName() + " ---- property name is :" + name);
}
public static void main(String[] args) {
Person person = new Person();
person.getName();
Student student = new Student();
student.getName();//继承类重写基类的方法
Person normalStudent = new Student();
normalStudent.getName();//动态编译,基类引用调用继承类方法
}
}
/**
* OUTPUT
* Class name is :Person ---- property name is :Person
* Class name is :Student ---- property name is :Student
* Class name is :Student ---- property name is :Student
*/
案例三中,继承类重写了getName方法,并且激活继承类的name属性(通过操作name属性的方式)。