先看一段Python代码
实现效果是子类和父类共用一个 sayHello()
方法,通过覆写属性name
输出不同的属性
class Parent(): name = "parent" def getName(self): return self.name def sayHello(self): print(self.name, "-", self.getName()) class Child(Parent): name = "child" if __name__ == "__main__": parent = Parent() print(parent.getName()) parent.sayHello() child = Child() print(child.getName()) child.sayHello()
输出效果满足预期要求
parent parent - parent child child - child
再来看Java代码
class Parent { private String name = "parent"; public String getName() { return name; } public void sayHello() { System.out.println(name + " - " + getName()); } } class Child extends Parent { private String name = "child"; } public class Demo { public static void main(String[] args) { Parent parent = new Parent(); System.out.println(parent.getName()); parent.sayHello(); Child child = new Child(); System.out.println(child.getName()); child.sayHello(); } }
输出结果和预期不一样
parent parent - parent parent parent - parent
修改一下子类,覆写父类的getName()
方法
class Parent { private String name = "parent"; public String getName() { return name; } public void sayHello() { System.out.println(name + " - " + getName()); } } class Child extends Parent { private String name = "child"; // 增加方法覆写 @Override public String getName() { return name; } } public class Demo { public static void main(String[] args) { Parent parent = new Parent(); System.out.println(parent.getName()); parent.sayHello(); Child child = new Child(); System.out.println(child.getName()); child.sayHello(); } }
输出结果看到,通过覆写方法获取属性的方式可以获取子类属性,直接获取的属性还是父类中的属性
parent parent - parent child parent - child