Java-inheritance, java inheritance
- Inherited initialization sequence
When we create an object, the constructor executed is equivalent to initializing an object.
Animal. java
Package com. test; public class Animal {public int age = 2; public String name; public void eat () {System. out. println ("animals can eat");} public Animal () {System. out. println ("animal constructor"); age = 4 ;}}
Dog. java
Package com. test; public class Dog extends Animal {public void eat () {System. out. println ("age" + age + "years old dogs can eat");} public Dog () {System. out. println ("dog constructor ");}}
Initail. java
package com.test;public class Initail { public static void main(String[] args) { Dog dog = new Dog(); //dog.age = 1; dog.eat(); }}
Run Initail. java. The execution result is as follows:
Animal Constructor
Dog Constructor
A 4-year-old dog can eat.
Using final keywords for identification has "final" meaning
Used inside an object to represent a parent class Object
The Object class is the parent class of all classes. If a class does not have extend and the keyword is clearly identified to inherit another class, this class inherits the Object class by default.
Methods In the Object class, suitable for all subclasses