Introduction to Java - Object Oriented - 01. Inheritance

Original address: http://www.work100.net/training/java-inheritance.html
More Tutorials: Beam Cloud - Free Course

inherit

Sequence Number Intratext chapters video
1 Summary -
2 Inheritance Features -
3 Inheritance keywords -
4 constructor -

See the navigation section above for reading

1. Overview

Inheritance is a cornerstone of java's object-oriented programming technology because it allows you to create hierarchical classes.

Inheritance is the inheritance of the parent's characteristics and behavior by a child class, so that the child class object (instance) has the instance domain and method of the parent class, or that the child class inherits the method from the parent class, so that the child class has the same behavior as the parent class.

Inheritance in life:

Rabbits and sheep are herbivores, lions and leopards are carnivores.

Herbivores and carnivores are also animals.

So the relationship that inheritance needs to conform to is-a, the parent class is more generic, and the child class is more specific.

Although both herbivores and carnivores are animals, there are differences in their attributes and behavior, so the subclass will have the general characteristics of the parent and will have its own characteristics.

Inheritance Format of Class

In Java, the extends keyword allows you to declare that one class inherits from another class in the following general form:

class parent {
}

Class subclass extends parent class {
}

Why inheritance is required

Next, we illustrate this requirement through an example.

To develop animals, including penguins and mice, which require the following:

  • Penguin: attribute (name, id), method (eat, sleep, self-introduction)
  • Mouse: attribute (name, id), method (eat, sleep, self-introduction)

Penguins:

public class Penguin { 
    private String name; 
    private int id; 
    public Penguin(String myName, int  myid) { 
        name = myName; 
        id = myid; 
    } 
    public void eat(){ 
        System.out.println(name+"I am eating"); 
    }
    public void sleep(){
        System.out.println(name+"Sleeping");
    }
    public void introduction() { 
        System.out.println("Hello everyone!I am" + id + "Number" + name + "."); 
    } 
}

Mouse:

public class Mouse { 
    private String name; 
    private int id; 
    public Mouse(String myName, int  myid) { 
        name = myName; 
        id = myid; 
    } 
    public void eat(){ 
        System.out.println(name+"I am eating"); 
    }
    public void sleep(){
        System.out.println(name+"Sleeping");
    }
    public void introduction() { 
        System.out.println("Hello everyone!I am" + id + "Number" + name + "."); 
    } 
}

From these two pieces of code, we can see that the code is duplicated, resulting in a large amount of code, bloated, and low maintainability (maintainability is mainly later need to modify, you need to modify a lot of code, easy to make mistakes), so to fundamentally solve the problem of these two pieces of code, you need to inherit, extract the same part of the two pieces of code to make upA parent class:

Common parent:

public class Animal { 
    private String name;  
    private int id; 
    public Animal(String myName, int myid) { 
        name = myName; 
        id = myid;
    } 
    public void eat(){ 
        System.out.println(name+"I am eating"); 
    }
    public void sleep(){
        System.out.println(name+"Sleeping");
    }
    public void introduction() { 
        System.out.println("Hello everyone!I am" + id + "Number" + name + "."); 
    } 
}

This Animal class can be used as a parent class. After penguins and mice inherit this class, they will have the attributes and methods of the parent class. The subclass will not have duplicate code, will be more maintainable, will be more concise, and will increase code reuse (reusability is mainly used multiple times, no longer having to write the same code multiple times)Code after inheritance:

Penguins:

public class Penguin extends Animal { 
    public Penguin(String myName, int myid) { 
        super(myName, myid); 
    } 
}

Mouse:

public class Mouse extends Animal { 
    public Mouse(String myName, int myid) { 
        super(myName, myid); 
    } 
}

Inheritance Type

It is important to note that Java does not support multiple inheritance, but it does support multiple inheritance.

2. Inheritance characteristics

  • Subclass has properties, methods that are not private ly owned by parent class
  • Subclasses can have their own properties and methods, that is, they can extend the parent
  • Subclasses can implement parent's methods in their own way
  • Java inheritance is single inheritance, but can be multiple inheritance. Single inheritance means that a subclass can only inherit one parent class. Multiple inheritance means, for example, class A inherits class B, class B inherits class C, so according to the relationship, class C is the parent class of class B, class B is the parent class of class A, which is a feature of Java inheritance different from C++ inheritance.
  • Enhanced coupling between classes (inheritance disadvantage, high coupling results in tighter code connections and less code independence)

3. Inherit keywords

Inheritance can be achieved using two keywords, extends and implements, and all classes inherit from java.lang.Object. When a class does not have two keywords inherited, the default inheritance object (this class is in the java.lang package, so import) ancestor class is not required.

extends keyword

In Java, class inheritance is a single inheritance, that is, a subclass can only have a parent class, so extends can inherit only one class.

public class Animal { 
    private String name;   
    private int id; 
    public Animal(String myName, String myid) { 
        //Initialize property values
    } 
    public void eat(){
        //Implementation of Eating Method  
    } 
    public void sleep() { 
        //Specific implementation of sleeping method  
    } 
} 

public class Penguin  extends  Animal {
}

implements keyword

Using the implements keyword disguises Java's multi-inheritance nature, using a range of class-inherited interfaces, and inheriting multiple interfaces simultaneously (with comma-separated interfaces).

public interface A {
    public void eat();
    public void sleep();
}

public interface B {
    public void show();
}

public class C implements A,B {
}

super and this keywords

Super keyword: We can use the super keyword to access the parent class members, referencing the parent class of the current object.

this keyword: refers to your own reference.

class Animal {
  void eat() {
    System.out.println("animal : eat");
  }
}

class Dog extends Animal {
  void eat() {
    System.out.println("dog : eat");
  }
  void eatTest() {
    this.eat();   // this calls its own method
    super.eat();  // super calls parent method
  }
}

public class Test {
  public static void main(String[] args) {
    Animal a = new Animal();
    a.eat();
    Dog d = new Dog();
    d.eatTest();
  }
}

The output is:

animal : eat
dog : eat
animal : eat

final keyword

The final keyword declares that a class can be defined as an inheritable, final class, or as a decorative method that cannot be overridden by subclasses:

  • Declare class:
final class class name { 
    //Class body 
}
  • Declare method:
Modifier (public/private/default/protected) final return value type method name (){
    //Method Body
}

Note: Instance variables can also be defined as final, and variables defined as final cannot be modified.Methods declared as final classes are automatically declared final, but instance variables are not final

4. Constructors

A subclass does not inherit its parent's constructor (constructor method or constructor), it is only called (implicit or explicit).If the constructor of the parent class has parameters, the constructor of the parent class must be explicitly invoked through the super keyword in the constructor of the child class with an appropriate list of parameters.

If the parent constructor has no parameters, then there is no need to call the parent constructor using the super keyword in the constructor of the child class, and the parameterless constructor of the parent class is automatically called.

Example

class SuperClass {
  private int n;
  SuperClass(){
    System.out.println("SuperClass()");
  }
  SuperClass(int n) {
    System.out.println("SuperClass(int n)");
    this.n = n;
  }
}
// SubClass Class Inheritance
class SubClass extends SuperClass{
  private int n;

  SubClass(){ // Automatically invoke parameterless constructor of parent class
    System.out.println("SubClass");
  }  

  public SubClass(int n){ 
    super(300);  // Call the constructor with parameters in the parent class
    System.out.println("SubClass(int n):"+n);
    this.n = n;
  }
}
// SubClass2 Class Inheritance
class SubClass2 extends SuperClass{
  private int n;

  SubClass2(){
    super(300);  // Call the constructor with parameters in the parent class
    System.out.println("SubClass2");
  }  

  public SubClass2(int n){ // Automatically invoke parameterless constructor of parent class
    System.out.println("SubClass2(int n):"+n);
    this.n = n;
  }
}
public class TestSuperSub{
  public static void main (String[] args){
    System.out.println("------SubClass Class Inheritance------");
    SubClass sc1 = new SubClass();
    SubClass sc2 = new SubClass(100); 
    System.out.println("------SubClass2 Class Inheritance------");
    SubClass2 sc3 = new SubClass2();
    SubClass2 sc4 = new SubClass2(200); 
  }
}

The output is:

------SubClass Class Inheritance------
SuperClass()
SubClass
SuperClass(int n)
SubClass(int n):100
------SubClass2 Class Inheritance------
SuperClass(int n)
SubClass2
SuperClass()
SubClass2(int n):200

Next: Rewrite and overload

Tags: Java Attribute Programming less

Posted on Fri, 06 Mar 2020 19:20:43 -0800 by SCook