current position:Home>12.16 Java inheritance

12.16 Java inheritance

2022-01-27 03:27:30 liheihei

  First : Inherit , Refers to the fact that one object directly uses the properties and methods of another object .

     Inherited format :

        • public class Subclass name entends Parent class name {}   /* Indicates that the previous subclass inherits the parent class */
        • example :public class Zi extends Fu{}

   The following is the code description :

/*
 *  Animal species , Parent class 
* This is a parent class
*/ public class Animal { private String name; private int age; private String color; public Animal(String name, int age, String color) { this.name = name; this.age = age; this.color = color; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public void show() { System.out.println(" Animal calls :"); } }

Next, let's create a subclass

/*
* This is a subclass of cats , It belongs to animals , So we inherit the above animals
*/
public
class Cat extends Animal { public Cat(String name, int age, String color) { super(name, age, color); super.show(); } public void show() { super.show(); System.out.println(" cat ..."); } }

Let's create a subclass

/*
* This is a subclass of dogs , Dogs also belong to animals , We can also inherit the animal class, that is, the parent class
*/
public
class Dog extends Animal{ public Dog(String name, int age, String color) { super(name, age, color); } public void show() { System.out.println(" Wang Wang Wang ..."); } }

Next , We create a new test class

public class AbimalDemo {

    public static void main(String[] args) {
        Dog dog1 = new Dog(" Li heihei ",6," gray ");
        System.out.println(dog1.getName()+"\t"+dog1.getAge()+"\t"+dog1.getColor());
        dog1.show();
        
        Cat cat1 = new Cat(" Song Maomao ",5," Pink ");
        System.out.println(cat1.getName()+"\t"+cat1.getAge()+"\t"+cat1.getColor());
        cat1.show();

    }

}

Let's look at the results :

 

 

  In the running result, we can see that the show Method, when we create a subclass object, we can call the result of the parent class That is, the sound of animals

 

To sum up :

     The advantage of inheritance is that subclasses can override the methods of the parent class to easily extend the parent class

       ①: The inner details of the parent class are visible to the child class .

       ②: The methods that subclasses inherit from their parents are determined at compile time , So you can't change the behavior of methods inherited from a parent class during runtime .

copyright notice
author[liheihei],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201270327281633.html

Random recommended