Everyone knows that subclass inheritance of parent classes is an inheritance of type, including attributes and methods! If the subclass and parent class have the same signature, it is called overwriting! If the attributes of the subclass and the parent class are the same, the parent class will hide its own attributes!
But if I use the references created by the parent class and the child class to point to the object created by the child class, what is the result of the property value or method in the child class object called?
Look at the code:
public class FieldDemo { public static void main(String[] args){ Student t = new Student("Jack"); Person p = t;//The reference created by the parent class points to the object created by the subclass System.out.println(t.name+","+p.name); System.out.println(t.getName()+","+p.getName()); } } class Person{ String name; int age; public String getName(){ return this.name; } } class Student extends Person{ String name; // The attribute and the parent class attribute name are the same, but it will not be the same as the parent class attribute name during development! ! public Student(String name){ this.name = name; super.name = "Rose"; // Assign value to attributes in the parent class} public String getName(){ return this.name; } } The return result is:
Jack, Rose
Jack, Jack
The reason is: in Java, attributes are bound to types and methods are bound to objects!
The article is very simple, but it also has certain practical value. I hope it will be helpful to everyone's learning.