Details the relationship between attributes methods and objects in Java inheritance

  • 2020-05-05 11:20:43
  • OfStack

Everyone knows that subclasses inherit from their superclasses, including properties and methods! If the subclass has the same method signature as the superclass, it's called overwrite! If the subclass has the same properties as the parent class, the parent class hides its properties!

But if I use a reference created by a parent class and a subclass to point to an object created by the subclass, what is the result of the parent class referencing a property value or method in the subclass object being called?

See the code:


public class FieldDemo { 
  public static void main(String[] args){ 
    Student t = new Student("Jack"); 
    Person p = t;// The parent class creates a reference to the object created by the child class   
    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; //  Property and parent class property name is the same, but when doing the development of the general and parent class property name is not the same!!   
  public Student(String name){ 
    this.name = name; 
    super.name = "Rose"; //  Assign values to properties in the parent class   
  } 
  public String getName(){ 
    return this.name; 
  } 
} 

The result is:
Jack,Rose
Jack,Jack

The reason: in Java, properties are bound to types and methods to objects!

The article is very simple, but also has certain practical value, I hope to help you in your study.


Related articles: