Polymorphism, Abstract class, interface, final keyword

Keywords: Java

Article Directory

final keyword

Represents the final, modifiable class, member variable, member method
1.final modifier becomes constant

 Modify local variables: You can temporarily leave the initial value unassigned, but only assign it once
 Modifier member variable: must give initial value

2.final-modified methods cannot be overridden and inherited by subclasses.

 Local variables accessing the outside world in anonymous internal classes prior to JDK1.8 need to be final, not after 1.8

polymorphic

An overview of polymorphism

Life: Different states of the same action in different environments
In Java: The same method reflects different states in different objects
In memory: parent reference points to child class object

Characteristics of polymorphic access members
  • Member variables: Look at the type on the left at compile time, compile error if there are no variables in the type on the left
    The runtime looks at the left type, and the value of the variable of the left type is the result of the run
    Compile left, execute left
  • Membership method:
    Compile to the left, execute to the right
  • Construction method:
    The polymorphic access subclass constructor first accesses the parent constructor
    Help subclasses initialize inherited members of the parent class
  • Static method:
    Compile left, execute left
Advantages of polymorphism

1. Simplified code
2. Improved maintainability and scalability

	public class DuoTaiDemo02 {
		public static void main(String[] args) {
			Fu fu = new Zi();
			System.out.println(fu.num); // 10
			fu.method();
			
			fu.show();
		}
	}
	
	class Fu {
	
		int num = 10;
	
		public void method() {
			System.out.println("Fu.method()");
		}
		
		public static void show() {
			System.out.println("Fu.show");
		}
	}
	
	class Zi extends Fu {
	
		int num = 20;
	
		@Override
		public void method() {
			System.out.println("Zi.method()");
		}
		
		public static void show() {
			System.out.println("Zi.show");
		}
		
	}
Disadvantages of polymorphism
You cannot access methods specific to subclasses using parent references

Solution downward transition:
Downward transition (coercion)
Format: <Subtype> <Reference Variable Name> = (<Subtype>) <Reference Variable of Parent Type>;
Characteristic:

 The parent class becomes a subclass, and the parent reference becomes a subclass object.Understand as forced type conversion
 During the downward transition, if you do not convert to a real subclass type, a type conversion exception (java.lang.ClassCastException) will occur.
 Exception resolution: Java provides a syntax for type judgment: instanceof
 Format: The result of this expression is that the boolean type tests whether the object on the left is an instance of the class on the right?

A downward transition naturally an upward transition
Upward Transition (Auto Transition)
Format: <parent type> <reference variable name> = new <subtype>();
Characteristic:
References to subclasses converted to parent classes point to subclass objects.Understand as automatic type conversion
The method invoked by a parent referencing a variable at this point is one that the child class overrides or inherits from the parent class
Subclass-specific properties and methods cannot be invoked by parent-class reference variables at this time

	public class DuoTaiDemo04 {
		public static void main(String[] args) {
	//		Car c = new BMW();
	//		c.run();
			
			// To access fillOil of BMW, no access
			// Take advantage of downward transition
	//		BMW bmw = (BMW) c;
	//		bmw.fillOil();
	//		
	//		c = new Benz();
	//		c.run();
			
	//		Benz benz = (Benz) c;
	//		benz.leakOli();
			
	//		BMW bmw2 = (BMW) c;
	//		bmw2.fillOil();
			
	//		System.out.println(c instanceof BMW);
	//		System.out.println(c instanceof Benz);
			Car c = new Benz();
			c.run();
			
			c = new BYD();
			c.run();
			
			if (c instanceof Benz) {
				Benz benz = (Benz) c;
				benz.leakOli();
			} else if (c instanceof BMW) {
				BMW b = (BMW) c;
				b.fillOil();
			} else  if (c instanceof BYD) {
				BYD byd = (BYD) c;
				byd.electric();
			}
			
			Object obj = new BMW();
			
		}
	}
	
	class Car {
		public void run() {
			System.out.println("Car.run()");
		}
	}
	
	class BMW extends Car {
		@Override
		public void run() {
			System.out.println("BMW.run()");
		}
		
		public void fillOil() {
			System.out.println("Come on.");
		}
	}
	
	class Benz extends Car {
		@Override
		public void run() {
			System.out.println("Benz.run()");
		}
		
		public void leakOli() {
			System.out.println("Oil spill");
		}
	}
	
	class BYD extends Car {
		@Override
		public void run() {
			System.out.println("BYD.run()");
		}
		
		public void electric() {
			System.out.println("Charge");
		}
	}

abstract class

An overview of abstract classes

Classes modified by the abstract keyword are called abstract classes.
Abstract class format: abstract class class name {}
Abstract class characteristics

Cannot be instantiated
 Abstract classes have constructors that initialize inherited members of the parent class
 Features of abstract methods
 Abstract methods have no method body
 Abstract methods must be in abstract classes
 An abstract method must be implemented in a subclass unless the subclass is an abstract class	

Matters needing attention

	 A method without a body in a class is an abstract method.
     A class that contains an abstract method is an abstract class.
     An abstract class does not necessarily contain an abstract method. If it contains an abstract method, it must be defined as an abstract class
     If a subclass does not implement all the abstract methods in an abstract base class, the subclass also becomes an abstract class.
     Constructor, static, private, final methods cannot be declared abstract.
     Members of abstract classes typically use public or protected
     Modifying abstract methods with private, final, static, and native has no method body, conflicts, or no meaning.

The difference between an abstract class and an ordinary class

What does it mean to have member variables, member methods, construction methods, static methods, constants in an abstract class?
Member Variables-->For Subclasses
 Member Method-->For Subclasses
 Constructor-->Helps subclasses initialize inherited members of the parent class
 Static Method-->Access directly through the class name to prevent undesired access to create objects
 Constant-->Yes, easy to access
 There is no difference between an abstract class and a normal class except that there are more abstract methods in an abstract class. 
Abstract methods of abstract classes force subclass overrides
 Non-abstract methods are used directly for subclasses
 Constructor and member variables are used directly for subclasses
 An abstract class is a complete service class that serves all subclasses     
	public class AbstractDemo01 {
		public static void main(String[] args) {
			// Shape s2 = new Shape();
			Shape s = new Triangle(2, 3, 4);
			System.out.println(s.getPerimeter());
			s = new Circle(1);
			System.out.println(s.getPerimeter());
			Shape.staticMethod();
			System.out.println(Shape.NUM);
	
		}
	}
	
	abstract class Shape {
		
		public static int NUM = 100;
		
		String name;
		
		public Shape() {}
		
		public Shape(String name) {
			this.name = name;
		}
		
		public abstract double getPerimeter();
	
		public abstract double getArea() ;
		
		public void setName(String name) {
			this.name = name;
		}
		
		public static void staticMethod() {
			System.out.println("Shape.staticMethod()");
		}
	}
	
	abstract class Square extends Shape {
		
	}
	
	class Rectangle extends Shape {
		double width;
		double length;
	
		public Rectangle() {
			super();
		}
	
		public Rectangle(String name, double width, double length) {
			super(name);
			this.width = width;
			this.length = length;
		}
	
		@Override
		public double getPerimeter() {
			return (width + length) * 2;
		}
	
		@Override
		public double getArea() {
			// TODO Auto-generated method stub
			return width * length;
		}
		
	}
	
	class Triangle extends Shape {
	
		double a;
		double b;
		double c;
	
		public Triangle() {
			super();
		}
	
		public Triangle(double a, double b, double c) {
			super();
			this.a = a;
			this.b = b;
			this.c = c;
		}
	
		public double getPerimeter() {
			return a + b + c;
		}
	
		@Override
		public double getArea() {
			// TODO Auto-generated method stub
			return 0;
		}
	}
	
	class Circle extends Shape {
		double r;
	
		public Circle() {
			super();
		}
	
		public Circle(double r) {
			super();
			this.r = r;
		}
	
		public double getPerimeter() {
			return 2 * Math.PI * r;
		}
	
		@Override
		public double getArea() {
			// TODO Auto-generated method stub
			return 0;
		}
	}

Interface

The concept of an interface:

In essence, an interface is a special abstract class that contains only the definitions of constants and abstract methods, without the implementation of variables and methods.

1. Interface is a standard, a specification, a convention
 2. Interfaces can extend functionality
 3. The interface is flexible and plug-and-play
 4. Interfaces are implemented by inheritors

Interface format:

   	format
   public interface interface name {
        //Constant
    	//Abstract Method
    }
    
    The implementation class format of the interface:
   	public class name implements interface {
      		//Methods for implementing interfaces
       		//General method
   }
   	Constant: Must be modified with public static final to omit.
    Method: public abstract modification must be used to omit.
Features of the interface
  1. Interface is decorated with interface
  2. Interfaces are a collection of constants and abstract methods
  	Constant: public static final is used by default
  	Method: Use public abstract modifier by default
  3. After JDK1.8, not only constant and abstract methods, but also default and static methods
  	The default method is used directly for subclasses, which can also be overridden on their own if they want to, without forcing overrides
  	Static methods are used to access directly through the interface name
  4. Interfaces cannot be instantiated
  5. Interfaces if you want to instantiate--using polymorphism
  6. Implementation class features of the interface:
  	If a class wants to implement an interface, it must implement all the abstract methods defined in the interface
 	If a class does not want to implement abstract methods in an interface, the implementation class is upgraded to an interface as well
Benefits of interfaces
Functions of Extended Classes
 Interface implements multiple inheritance, communication and interaction between class and any subclass that implements interface
 More flexible interfaces, commonly used in development
Differences between interfaces and abstract classes

	public class InterfaceDemo01 {
		public static void main(String[] args) {
	//		System.out.println(Inter.num);
			
	//		Inter.num = 200;
			
	//		Inter.staticMethod();
			
	//		Inter inter = new Inter();
			
	//		Utilizing polymorphism
			Inter inter = new InterImpl();
		}
	}
	
	interface Inter {
	//	int num = 100;
		public static final int NUM = 100;
		
		void show();
		
		void method();
		
		// Default Method
		public default void defaultMethod() {
			System.out.println("Inter.defaultMethod()");
		}
		
		// Static method
		public static void staticMethod() {
			System.out.println("Inter.staticMethod()");
		}
	}
	
	class InterImpl implements Inter {
	
		@Override
		public void show() {
			System.out.println("InterImpl.show()");
		}
	
		@Override
		public void method() {
			System.out.println("InterImpl.method()");
		}
		
	}
	
	interface InterSon extends Inter {
		
	}	

Posted by Humpty on Thu, 16 May 2019 16:56:40 -0700