The inheritance of objects is accomplished through extends in Java
The code is as follows:
Package Hello;class person{private string name;private int age;public string getName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;}} Class Student extends Person{public void Tell () {System.out.println (GetName () + "+ Getage ())}} public class Extendsdemo {public static void main (string[] args) {Student Student = new Student (); student.setage; stude Nt.setname ("Zhangsan"); Student.tell ();}}
We pass
Class Student extends Person
To complete the Student object's inheritance of the person object, which in Student can access the properties and methods in the parent class, and, of course, in the example above, the private attribute (name and age) in the parent class is encapsulated by private and therefore requires the getName and Getage to complete its visit.
Two restrictions on inheritance:
1. You can inherit only one object in Java (multiple objects can be inherited in Python)
2. Subclasses cannot directly access private properties in the parent class
About the instantiation process of a subclass object
Before a subclass object is instantiated, the constructor method in the parent class must be called before the child class is called. The code is as follows:
Package Hello;class Father{public Father () {System.out.println ("constructor method for parent class");}} Class Son extends Father{public son () {System.out.println ("constructor method of the subclass");}} public class Extendsdemo {public static void main (string[] args) {son son = new Son ();}}
Program output:
How to construct a child class of a parent class
Inheritance of three major features of Java