Java OOP inheritance

Posted by Anidazen on Fri, 12 Jun 2020 10:43:12 +0200

1, The concept of inheritance

Inheritance is a cornerstone of java object-oriented programming technology, because it allows the creation of hierarchical classes.

Inheritance means that the subclass inherits the characteristics and behaviors of the parent class, making the subclass object (instance) have the instance domain and methods of the parent class, or the subclass inherits the methods from the parent class, making the subclass have the same behaviors of the parent class.

eg:

Rabbits and sheep belong to herbivores, lions and leopards belong to carnivores.

Herbivores and carnivores belong to animals.

Therefore, inheritance needs to conform to the following relations: is-a, the parent class is more general, and the child class is more specific.

Although herbivores and carnivores belong to animals, there are differences in their properties and behaviors, so the subclass will have the general characteristics of the father as well as its own characteristics.

Inheritance syntax of class

In Java, the extensions keyword can be used to declare that a class is inherited from another class. The general form is as follows:

class parent{

}

Class subclass extends parent class{

}

give an example:

//Animal Fathers
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 other Animal classes inherit this class, they will have the properties and methods in the parent class. There will be no duplicate code in the child class. The maintainability will be improved, and the code will be more concise. The reusability of the code will be improved (if the reusability can be used many times, the same code will not be written many times). The inherited Code:

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

Inherited properties:

  • The child class has the non private property and method of the parent class.
  • Subclasses can have their own properties and methods, that is, subclasses can extend the parent class.
  • Subclasses can implement the methods of their parents in their own way.
  • Java inheritance is single inheritance, but it can be multiple inheritance. Single inheritance is that a subclass can only inherit one parent class. Multiple inheritance is that, for example, class a inherits class B, and class B inherits class C, so according to the relationship, class C is the parent class of class B, and class B is the parent class of class A, which is a feature of Java inheritance different from C + + inheritance.
  • It improves the coupling between classes (the disadvantage of inheritance, high coupling will cause the connection between codes).

Inherit keywords

Inheritance can be implemented by using the keywords extensions and implements, and all classes inherit from the java.lang.Object When a class does not inherit two keywords, it inherits object by default java.lang Package, so no import) ancestor class is required.

extends keyword

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

public class Animal { 
    private String name;   
    private int id; 
    public Animal(String myName, String myid) { 
        //Initialize property value
    } 
    public void eat() {  //The concrete realization of eating method} 
    public void sleep() { //The concrete realization of sleeping method} 
} 
 
public class Penguin  extends  Animal{ 
}

implements keyword

Using the implements keyword can make java have the feature of multiple inheritance in disguise. If the scope of use is class inheritance interface, multiple interfaces can be inherited at the same time (comma separated interface and interface)

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 access the parent class members through the super keyword, which is used to reference the parent class of the current object, similar to the base keyword we learned in C ා.

This keyword: refers to its own reference, a member property in this class.

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 the parent method
  }
}
 
public class Test {
  public static void main(String[] args) {
    Animal a = new Animal();
    a.eat();
    Dog d = new Dog();
    d.eatTest();
  }
}

Output results:

animal : eat
dog : eat animal : eat

final keyword

The final keyword declares that a class can be defined as an inheritable, final class, or used to modify a method that cannot be overridden by a subclass:

  • Declaration class:

    final class class name {/ / class body}
  • Declaration method:

    Modifier (public/private/default/protected) final return value type method name () {/ / method body}
  • Many of the classes provided by Java are final classes (final classes, classes that cannot be inherited), such as String classes and Math classes. They can no longer have subclasses. Some methods in the Object class, such as getclass(). Notify(), wait(), are all final methods, which can only be inherited by subclasses and cannot be overridden. However, hashCode(),toString(),equals(Object obj) are not final methods and can be overridden.

Note: instance variables can also be defined as final. Variables defined as final cannot be modified. Methods declared as final classes are automatically declared as final, but instance variables are not final and will not be automatically declared. Not all of the final classes are constants.

abstract keyword

abstract and final are two keywords with opposite functions. They are comparative memory

  • Abstract can be used to modify classes and methods, called abstract classes and methods, not to modify properties and construction methods. final can be used to modify classes, methods, and properties, not constructor.
  • Abstract cannot modify a method at the same time as private and static, because abstract methods must be rewritten in subclasses. How to rewrite private methods? An abstract method without implementation cannot be modified with static. Cannot modify a method or class at the same time with final. Abstract class is inherited by subclass and rewrites the abstract method of parent class. Similarly, abstract class can only be instantiated by subclass inheritance, which is contradictory. But it does not conflict with the public keyword.

Summary of access modifiers in Java:

constructor

The subclass cannot inherit the constructor (constructor or constructor) of the parent class, but if the constructor of the parent class has parameters, the constructor of the parent class must be explicitly called through the super keyword in the constructor of the subclass and matched with the appropriate parameter list. It is similar to the base keyword in c ා, but it is written differently from the call.

If the parent class has a parameter free constructor, it is not necessary to call the parent class constructor with super in the constructor of the child class. If the super keyword is not used, the system will automatically call the parameter free constructor of the parent class.

class SuperClass {
  private int n;
  SuperClass(){
    System.out.println("SuperClass()");
  }
  SuperClass(int n) {
    System.out.println("SuperClass(int n)");
    this.n = n;
  }
}
class SubClass extends SuperClass{
  private int n;
  
  SubClass(){
    super(300);
    System.out.println("SubClass");
  }  
  
  public SubClass(int n){
    System.out.println("SubClass(int n):"+n);
    this.n = n;
  }
}
public class TestSuperSub{
  public static void main (String args[]){
    SubClass sc = new SubClass();
    SubClass sc2 = new SubClass(200); 
  }
}

Output results:

SuperClass(int n) SubClass SuperClass() SubClass(int n):200

Java override and overload

Override

Rewriting is the process that a subclass rewrites the implementation of the method that the parent class allows access to. Neither the return value nor the parameter can be changed. (that is, the shell is unchanged, and the core is rewritten!)

The advantage of overriding is that subclasses can define their own behavior as needed. That is to say, the subclass can implement the methods of the parent class as needed.

An overriding method cannot throw a new check Exception or an Exception that is broader than the overridden method declaration. For example: a method of the parent class declares a check Exception IOException, but when overriding this method, Exception exception Exception cannot be thrown, because Exception is the parent class of IOException, only the child class Exception of IOException can be thrown.

give an example:

class Animal{
   public void move(){
      System.out.println("Animals can move");
   }
}
 
class Dog extends Animal{
   public void move(){
      System.out.println("Dogs can run and walk");
   }
}
 
public class TestDog{
   public static void main(String args[]){
      Animal a = new Animal(); // Animal object
      Animal b = new Dog(); // Dog object
 
      a.move();// Methods for executing the Animal class
 
      b.move();//Methods to execute the Dog class
   }
}

Override rules for methods

  • The parameter list must be exactly the same as the overridden method;
  • The return type must be exactly the same as the return type of the overridden method;
  • Access cannot be lower than that of the overridden method in the parent class. For example, if a method of a parent class is declared public, overriding the method in a child class cannot be declared protected.
  • A member method of a parent class can only be overridden by its child class.
  • Methods declared as final cannot be overridden.
  • Methods declared static cannot be overridden, but can be declared again.
  • If the subclass and the parent are in the same package, then the subclass can override all the methods of the parent except those declared as private and final.
  • If the subclass and the parent are not in the same package, then the subclass can only override the non final methods declared as public and protected by the parent.
  • The overridden method can throw any non mandatory exception, regardless of whether the overridden method throws an exception or not. However, the overridden method cannot throw a new mandatory exception, or a broader mandatory exception than the one declared by the overridden method, otherwise it can.
  • The constructor cannot be overridden.
  • If you cannot inherit a method, you cannot override it.

Use of Super keyword

When you need to call a rewrite method of a parent class in a subclass, use the super keyword.

class Animal{
   public void move(){
      System.out.println("Animals can move");
   }
}
 
class Dog extends Animal{
   public void move(){
      super.move(); // Methods of applying super class
      System.out.println("Dogs can run and walk");
   }
}
 
public class TestDog{
   public static void main(String args[]){
 
      Animal b = new Dog(); // Dog object
      b.move(); //Methods to execute the Dog class
 
   }
}

Overload

Overloading is in a class, with the same method name and different parameters. The return type can be the same or different.

Each overloaded method (or constructor) must have a unique list of parameter types.

The most common is the overloading of constructors.

Overload rule:

  • The overloaded method must change the parameter list (the number or type of parameters are different);
  • Overloaded methods can change the return type;
  • Overloaded methods can change access modifiers;
  • Overloaded methods can declare new or broader check exceptions;
  • Methods can be overloaded in the same class or in a subclass.
  • The return value type cannot be used as a differentiator for overloaded functions.
public class Overloading {
    public int test(){
        System.out.println("test1");
        return 1;
    }
 
    public void test(int a){
        System.out.println("test2");
    }   
 
    //The following two parameter types are in different order
    public String test(int a,String s){
        System.out.println("test3");
        return "returntest3";
    }   
 
    public String test(String s,int a){
        System.out.println("test4");
        return "returntest4";
    }   
 
    public static void main(String[] args){
        Overloading o = new Overloading();
        System.out.println(o.test());
        o.test(1);
        System.out.println(o.test(1,"test3"));
        System.out.println(o.test("test4",1));
    }
}

The difference between rewriting and overloading

summary

Overriding and overloading of methods are different manifestations of java polymorphism. Overriding is a manifestation of polymorphism between parent and child classes. Overloading can be understood as a concrete manifestation of polymorphism.

  • (1) Method overloading is defined in a class with multiple methods with the same name, but with different or the same number of parameters and different types and orders, it is called method overloading.
  • (2) Method overriding is a method that has the same name as the method of the parent class, the same number and type of parameters, and the same return value. It is called overriding.
  • (3) Method overloading is a polymorphic representation of a class, while method rewriting is a polymorphic representation of a subclass and a parent class.

Abstract classes and abstract methods

In the concept of object-oriented, all objects are described by classes, but conversely, not all classes are used to describe objects. If a class does not contain enough information to describe a specific object, such a class is an abstract class.

In addition to being unable to instantiate an object, other functions of an abstract class still exist. Member variables, member methods, and construction methods are accessed in the same way as ordinary classes.

Because abstract classes cannot instantiate objects, they must be inherited before they can be used. For this reason, it is usually decided at the design stage whether to design abstract classes or not.

The parent class contains common methods for the collection of subclasses, but because the parent class itself is abstract, these methods cannot be used.

In Java, an abstract class represents an inheritance relationship. A class can only inherit one abstract class, while a class can implement multiple interfaces.

Abstract class is used to define abstract class in Java language.

/* File name: Employee.java */
public abstract class Employee
{
   private String name;
   private String address;
   private int number;
   public Employee(String name, String address, int number)
   {
      System.out.println("Constructing an Employee");
      this.name = name;
      this.address = address;
      this.number = number;
   }
   public double computePay()
   {
     System.out.println("Inside Employee computePay");
     return 0.0;
   }
   public void mailCheck()
   {
      System.out.println("Mailing a check to " + this.name
       + " " + this.address);
   }
   public String toString()
   {
      return name + " " + address + " " + number;
   }
   public String getName()
   {
      return name;
   }
   public String getAddress()
   {
      return address;
   }
   public void setAddress(String newAddress)
   {
      address = newAddress;
   }
   public int getNumber()
   {
     return number;
   }
}

We can't instantiate an employee class object, but if we instantiate a Salary class object, the object will inherit 7 member methods from the Employee class, and three member variables can be set or obtained through this method.

/* File name: AbstractDemo.java */
public class AbstractDemo
{
   public static void main(String [] args)
   {
      Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
      Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);
 
      System.out.println("Call mailCheck using Salary reference --");
      s.mailCheck();
 
      System.out.println("\n Call mailCheck using Employee reference--");
      e.mailCheck();
    }
}

Abstract method

If you want to design a class that contains a special member method whose implementation is determined by its subclass, you can declare the method as an abstract method in the parent class.

The Abstract keyword can also be used to declare Abstract methods, which contain only one method name and no method body.

Abstract methods are undefined, and the method name is followed by a semicolon instead of curly braces.

public abstract class Employee
{
   private String name;
   private String address;
   private int number;
   
   public abstract double computePay();
   
   //Remaining codes
}

Declaring an abstract method results in the following two results:

  • If a class contains abstract methods, the class must be abstract.
  • Any subclass must override the abstract method of the parent class or declare itself an abstract class.

Subclasses that inherit abstract methods must override the method. Otherwise, the subclass must also be declared as an abstract class. Finally, there must be subclasses to implement the abstract method, otherwise, neither the original parent class nor the final subclass can be used to instantiate the object.

If the Salary class inherits the Employee class, it must implement the computePay() method:

/* File name: Salary.java */
public class Salary extends Employee
{
   private double salary; // Annual salary
  
   public double computePay()
   {
      System.out.println("Computing salary pay for " + getName());
      return salary/52;
   }
 
   //Remaining codes
}

Abstract class summary

  • 1. The abstract class cannot be instantiated (an easy mistake for beginners). If it is instantiated, an error will be reported and the compilation cannot pass. Only non Abstract subclasses of abstract classes can create objects.
  • 2. Abstract classes do not necessarily contain abstract methods, but the classes with abstract methods must be abstract classes.
  • 3. The abstract method in the abstract class is just a declaration, does not contain the method body, that is, does not give the concrete implementation of the method, that is, the concrete function of the method.
  • 4. Construct methods. Class methods (Methods decorated with static) cannot be declared as abstract methods.
  • 5. The subclass of an abstract class must give the concrete implementation of the abstract method in the abstract class, unless the subclass is also an abstract class.

Topics: Java Programming shell