Java Introductory Tutorial||Java Polymorphism||Java Abstract Class

Java polymorphism

This chapter mainly introduces the concept of java polymorphism and simple examples of polymorphism that are easy to understand.

Java polymorphism


Polymorphism is the ability to have multiple different manifestations or morphologies of the same behavior.

Polymorphism is the embodiment of multiple manifestations of objects.

For example, when we talk about the object "pet", it has many different expressions or realizations, such as kittens, puppies, lizards, and so on. Then I go to the pet store and say "please give me a pet", the waiter can give me a kitten, puppy or lizard, we say that the object of "pet" has polymorphism.

Next, let us understand Java's polymorphism through examples.

simple example

public interface Vegetarian{}
public class Animal{}
public class Deer extends Animal implements Vegetarian{}

Because the Deer class has multiple inheritance, it is polymorphic. The above example is analyzed as follows:

  • A Deer IS-A (is a) Animal
  • A Deer IS—A (is a) Vegetarian
  • A Deer IS-A (is a) Deer
  • A Deer IS-A (is a) Object

In Java, all objects are polymorphic, because any object can pass the IS-A test type and Object class.

The only way to access an object is through a reference variable.

A reference variable can only have one type, and once declared, the type of a reference variable cannot be changed.

Reference variables can not only be reset to other objects, provided that these objects are not declared final. It can also refer to objects of the same or compatible type. It can be declared as a class type or an interface type.

When we apply a reference variable to a reference to a Deer object, the following declarations are legal:

Deer d = new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;

All reference variables d, a, v, o point to the same Deer object in the heap.


virtual method

We'll describe how the behavior of overridden methods affects polymorphism when designing classes in Java.

We have already discussed method overriding, that is, subclasses can override parent class methods.

When a subclass object calls an overridden method, the method of the subclass is called, not the overridden method in the parent class.

To call the overridden method in the parent class, the keyword super must be used.

/* 文件名 : Employee.java */
public 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 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;
   }
}

Suppose the following class inherits from the Employee class:

/* 文件名 : Salary.java */
public class Salary extends Employee
{
   private double salary; //Annual salary
   public Salary(String name, String address, int number, double
      salary)
   {
       super(name, address, number);
       setSalary(salary);
   }
   public void mailCheck()
   {
       System.out.println("Within mailCheck of Salary class ");
       System.out.println("Mailing check to " + getName()
       + " with salary " + salary);
   }
   public double getSalary()
   {
       return salary;
   }
   public void setSalary(double newSalary)
   {
       if(newSalary >= 0.0)
       {
          salary = newSalary;
       }
   }
   public double computePay()
   {
      System.out.println("Computing salary pay for " + getName());
      return salary/52;
   }
}

Now let's read the following code carefully and try to give its output:

/* 文件名 : VirtualDemo.java */
public class VirtualDemo
{
   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();
    }
}

The result of compiling and running the above example is as follows:

Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0

Call mailCheck using Employee reference--
Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.0

In the example, we instantiate two Salary objects. One uses Salary references and the other uses Employee references.

When compiling, the compiler checks the declaration of the mailCheck() method in the Salary class.

When s.mailCheck() is called, the Java Virtual Machine (JVM) calls the mailCheck() method of the Salary class.

Because e is a reference to Employee, calling e's mailCheck() method has completely different results.

When the compiler checks the e.mailCheck() method, the compiler checks into the mailCheck() method in the Employee class.

At compile time, the compiler uses the mailCheck() method in the Employee class to verify the statement, but at runtime, the Java Virtual Machine (JVM) calls the mailCheck() method in the Salary class.

This behavior is called a virtual method call and the method is called a virtual method.

All methods in Java can be represented in this way, whereby the overridden method can be invoked at runtime, regardless of the data type of the variable referenced in the source code at compile time.

Java abstract class

In the Java object-oriented concept, 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.

Except that the abstract class cannot instantiate objects, other functions of the class still exist, and the access methods of member variables, member methods and construction methods are the same as ordinary classes.

Since abstract classes cannot instantiate objects, abstract classes must be inherited before they can be used. It is also for this reason that it is usually decided at the design stage whether to design an abstract class.

The parent class contains common methods for subclass collections, but since the parent class itself is abstract, these methods cannot be used.


abstract class

Abstract class is used in the Java language to define abstract classes. Examples are as follows:

/* 文件名 : 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;
   }
}

Note that the Employee class is no different. Although the class is abstract, it still has 3 member variables, 7 member methods, and 1 constructor. Now if you try the following example:

/* 文件名 : AbstractDemo.java */
public class AbstractDemo
{
   public static void main(String [] args)
   {
      /* 以下是不允许的,会引发错误 */
      Employee e = new Employee("George W.", "Houston, TX", 43);

      System.out.println("\n Call mailCheck using Employee reference--");
      e.mailCheck();
    }
}

When you try to compile the AbstractDemo class, the following error occurs:

Employee.java:46: Employee is abstract; cannot be instantiated
      Employee e = new Employee("George W.", "Houston, TX", 43);
                   ^
1 error

inherit abstract class

We can extend the Employee class in the usual way:

/* 文件名 : Salary.java */
public class Salary extends Employee
{
   private double salary; //Annual salary
   public Salary(String name, String address, int number, double
      salary)
   {
       super(name, address, number);
       setSalary(salary);
   }
   public void mailCheck()
   {
       System.out.println("Within mailCheck of Salary class ");
       System.out.println("Mailing check to " + getName()
       + " with salary " + salary);
   }
   public double getSalary()
   {
       return salary;
   }
   public void setSalary(double newSalary)
   {
       if(newSalary >= 0.0)
       {
          salary = newSalary;
       }
   }
   public double computePay()
   {
      System.out.println("Computing salary pay for " + getName());
      return salary/52;
   }
}

Although we cannot instantiate an object of the Employee class, if we instantiate an object of the Salary class, the object will inherit 3 member variables and 7 member methods from the Employee class.

/* 文件名 : 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();
    }
}

The result of compiling and running the above program is as follows:

Constructing an Employee
Constructing an Employee
Call mailCheck using  Salary reference --
Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0

Call mailCheck using Employee reference--
Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.

abstract method

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

The Abstract keyword can also be used to declare an abstract method, which only contains a method name without a method body.

Abstract methods are not defined, and the method name is directly 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();
   
   //其余代码
}

Declaring an abstract method has two consequences:

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

Subclasses that inherit an abstract method must override this method. Otherwise, the subclass must also be declared abstract. Ultimately, there must be subclasses that implement this abstract method, otherwise, neither the initial parent class nor the final subclass can be used to instantiate objects.

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

/* 文件名 : 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;
   }

   //其余代码
}

Guess you like

Origin blog.csdn.net/m0_69824302/article/details/130349537