JAVA foundation 06 - interface and polymorphism

1, Interface

1.1 what is the interface

First of all, explain the rookie tutorial, which is very professional

Interface (English: Interface), an abstract type in JAVA programming language, is a collection of abstract methods. Interfaces are usually declared as interfaces. A class inherits the abstract methods of the interface by inheriting the interface.

Interfaces are not classes. The way of writing interfaces is very similar to that of classes, but they belong to different concepts. Class describes the properties and methods of an object. Interface contains the methods to be implemented by the class.

Unless the class implementing the interface is an abstract class, the class should define all methods in the interface.

The interface cannot be instantiated, but it can be implemented. A class that implements an interface must implement all the methods described in the interface, otherwise it must be declared as an abstract class. In addition, in Java, interface types can be used to declare a variable. They can become a null pointer or be bound to an object implemented by this interface.

We can try a simple understanding:

As the name suggests, the interface is an access port, just like various interfaces of hardware. It is necessary to follow certain specifications and connect the program to achieve the effect of data connection, just as the current is sent to electrical equipment through the power interface.

The interface is abstract, just like the hardware interface. Some interfaces look strange and are designed to access specific equipment. Some interfaces are invisible and unimaginable inside the equipment. By analogy, it's easier to understand that the program interface is an abstract class.

The interface is not a class, just like the USB interface is not a USB disk, but the USB interface determines the type of device connected and must support USB.

The interface cannot be instantiated. It can be understood that the interface of hardware does not directly participate in the work of devices.

1.2 function of interface

After understanding the definition of the interface, we can understand that the interface definition is a specification.

For example, the USB interface standardizes a certain access mode: how big the USB port is, how many data cables are there, and so on.

The method in the interface is to extract the common method of the class implementing the interface, and the class implementing the interface must be rewritten.

1.3 definition and use of interface

1.3.1 create interface:

public interface Interface name{
    //Constant. Because the interface defines a specification, there can be only constants and no variables
    public static final Constant type constant name = constant value;
    
    /**Abstract method*/
    public abstract Return value type method name();
    
    //Because the interface is a kind of specification and there are few places that can be changed, the keywords of constants and abstract methods can be abbreviated as:
    //Abbreviated constants:
    Constant type constant name = constant value;
    
    /**Abbreviated abstract method*/
    Return value type method name();
    
}

Abstract method: it is modified by abstract and has no method body.

It is worth noting that after jdk 1.8, methods with method bodies can also be defined in the interface, which are called default methods and decorated with default.

1.3.2 implementation interface:

public class Class name implements Interface name 1, interface name 2... {
    /**
    *Override all abstract methods
    */
    ...
}

The implemented interface can be more than one, and all abstract methods must be rewritten. This is the definition and embodiment of interface commonality.

1.4 interface examples

Define an interface:

/**
 * This class is used to learn interface
 * @author Sharry
 * */
public interface BasicAction {
	//constant
	int HP = 100;
	
	/**Abstract method, definition*/
    void eat();
}

Implementation class:

public class Human implements BasicAction {

	@Override
	public void eat() {
		// TODO Auto-generated method stub
		System.out.println("Food is the most important thing for the people");
	}

}

2, Polymorphism

Polymorphism is one of the three characteristics of object-oriented. How to understand polymorphism in the early stage? As the name suggests: multiple states. For example: monsters can have a variety of States, including blue eyed white dragons and black magicians; Black magician and blue eyed white dragon are monsters, but their attack power, attributes and race are different. This is the polymorphism of monsters.

The premise of polymorphism is inheritance and rewriting.

2.1 role of polymorphism

Since polymorphism is a variety of States, the function of polymorphism is to improve code reusability, flexibility and expansibility.

2.2 upward modeling

/**Parent Monster*/
public class Monster {

	//aggressivity
	private int attackPower;
	//Defensive power
	private int defendPower;
	//Number of stars
	private int starLevel;
    
    //effect
	private String funtion;
    
    //action
    public String attack() {
    	return "Attacking!";
    }

    //Construction method
	public Monster(int attackPower, int defendPower, int starLevel, String funtion) {
		super();
		this.attackPower = attackPower;
		this.defendPower = defendPower;
		this.starLevel = starLevel;
		this.funtion = funtion;
	}

	public Monster() {
		//Parameterless construction, where super calls the method of the parent class Object. Everything is an Object!
		super();
	}

	public int getAttackPower() {
		return attackPower;
	}

	public void setAttackPower(int attackPower) {
		this.attackPower = attackPower;
	}

	public int getDefendPower() {
		return defendPower;
	}

	public void setDefendPower(int defendPower) {
		this.defendPower = defendPower;
	}

	public int getStarLevel() {
		return starLevel;
	}

	public void setStarLevel(int starLevel) {
		this.starLevel = starLevel;
	}

	public String getFuntion() {
		return funtion;
	}

	public void setFuntion(String funtion) {
		this.funtion = funtion;

	}
}
/**Subclass blue eyed white dragon inheritance monster*/
public class BlueEyesWhiteDragon extends Monster {
	//The name of blue eyed white dragon is fixed and cannot be modified, so it is modified by final. Final can also be used with static
		private static final String name = "BlueEyeWhiteDragon";
		
		//super keyword to call the parent class method
		public void testSuper() {
			super.attack();
		}
		
		//Overloading of methods
		public void testSuper(int j) {
			System.out.println(j);
		}
		
		//This is the rewriting of the method, annotated with @ Override annotation
		@Override
		public String attack() {
			return "Explosive blast bomb of destruction";
			
		}
		
		
}

//Upward modeling in test class
/Embodiment of polymorphism	
//Shape up: the parent class points to the child class. Monsters can be blue eyed white dragons.
		Monster b1 = new BlueEyesWhiteDragon();
		System.out.println(b1.attack());
		

2.3 downward transformation

//In the downward transformation, the blue eyed white dragon is also a monster, but pay attention to the strong transformation of type and instanceOf
		//BlueEyesWhiteDragon b2 = (BlueEyesWhiteDragon) new Monster();  This sentence will report an exception
		if(b1 instanceof Monster){
			b1 = new Monster();
			System.out.println(b1.attack());
		}else {
			System.out.println("Your blue eyed white dragon has the wrong inheritance");
		}

Downward transformation is usually used with upward modeling. During the transformation, we sometimes need to consider the problem of threads, and we also need instance of to make if judgment or double if null judgment. Here, as an expansion of knowledge - put it on the branch task to learn, consolidate and complete slowly.

3, Abstract class

3.1 what are abstract classes

When a class has abstract methods, the class must be declared as an abstract class, so the abstract class must be inherited and overridden by subclasses to make the defined abstract methods meaningful.

Declaration keyword: abstract

3.1.1 differences between abstract classes and interfaces: (carried from Baidu Encyclopedia)

(1) Abstract classes should be inherited by subclasses, extensions; The implementation class of the interface is implementation.

(2) Interfaces can only make method declarations, and abstract classes can make method declarations or method implementations.

(3) The variables defined in the interface can only be public static constants, and the variables in the abstract class are ordinary variables.

(4) The result of refactoring is the abstraction of the class.

(5) Abstract classes and interfaces are used to abstract concrete objects, but the interface has the highest level of abstraction.

(6) Abstract classes can have concrete methods and properties, and interfaces can only have abstract methods and immutable constants.

(7) Abstract classes are mainly used to abstract classes, and interfaces are mainly used to abstract functions.

3.1.2 characteristics of abstract classes

(1) Abstract classes cannot be instantiated directly

(2) Subclasses can only inherit one abstract class, and the abstract method of the abstract class must be overridden

(3) Abstract classes can have no abstract methods

3.2 functions of abstract classes

Abstract classes are also the extraction of common methods of subclasses, which can also increase code reusability and flexibility.

Abstract classes prefer to share subclasses, but implement different methods to extract from the upper layer.

3.3 definition and use of abstract classes

/**Define a simple small abstract class demo*/
abstract class AbstractClass {

	abstract void eat();

}

Subclass inheritance and override method:

public class AbstractSonClass extends AbstractClass {

	@Override
	void eat() {
		// TODO Auto-generated method stub
		System.out.println("eating");
	}

	public static void main(String[] args) {
		AbstractSonClass abstractSonClass = new AbstractSonClass();
		abstractSonClass.eat();
	}

}

3.4 rewriting and reconstruction

Here is a supplementary extension of the concept of rewriting and reconstruction.

The rewriting method has the same name, but its implementation or permission and return value type can be different.

Refactoring also belongs to rewriting, that is, a way of rewriting, but refactoring focuses more on the implementation of methods. The rest are the same.

Therefore, although the implementation of abstract methods by subclasses can be called rewriting, they actually pay more attention to the reconstruction of methods.

The specific differences between covering, rewriting, refactoring and overloading can be learned as branch tasks.

4, Inner class

An inner class is an object in which a class is declared and used

4.1 static internal class

Declare an inner class decorated with static in a class

/**
*@Author Sharry
*@Version V1.0
*Description:Internal class learning
*/
public class InnerClass {

	//Attributes and methods
	private static int hp = 100;
	
	public void attack() {
		System.out.println("Attacking");
	}
	
	//Static inner class
	static class StaticInnerClass {
		//Attributes
		private int age;
		
		public void eat() {
		   //Static internal classes cannot directly call methods and properties of external classes, unless they are static modified class properties and methods
			System.out.println(InnerClass.hp);
		   System.out.println("eating");	
		}
		
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
        //Instantiate static internal class: click through the class name
		InnerClass.StaticInnerClass innerClass = new InnerClass.StaticInnerClass();
		innerClass.eat();
	}

}

Through this example, we can consolidate the methods and classes modified by static keyword. Generally, we can only call the methods and properties modified by static.

In addition, because this class is modified by static, you can use an external class name Create an instance with a static internal class name.

4.2 non static inner class

Class to declare another class

public class InnerClass {

	//Attributes and methods
	private static int hp = 100;
	
	public void attack() {
		System.out.println("Attacking");
	}
	
	//Static inner class
	static class StaticInnerClass {
		//Attributes
		private int age;
		
		public void eat() {
		   //Static internal classes cannot directly call methods and properties of external classes, unless they are static modified class properties and methods
			System.out.println(InnerClass.hp);
		   System.out.println("eating");	
		}
		
	}
	
	//General internal class
	class NormalInnerClass {
		
		//Attributes
		private String name;
		
		public void run() {
			System.out.println("running");
		}
		
		
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
        //Instantiate static internal class: click through the class name
		InnerClass.StaticInnerClass staticInnerClass = new InnerClass.StaticInnerClass();
		staticInnerClass.eat();
		
		//Instantiate inner class
		//1. Instantiated external classes
		InnerClass innerClass = new InnerClass();
		//2. Click through the external class object
		NormalInnerClass normalInnerClass = innerClass.new NormalInnerClass();
	}

}

Non - static internal classes need to create objects through external classes first, and then through objects Create object with new class name

4.3 anonymous inner class

When declaring a class, instantiate it on site, and use it directly without naming.

Anonymous inner classes are often used for rapid subclass creation of interfaces and abstract methods.

/**
*@Author Sharry
*@Time 2021 12:20:11 PM, December 3
*@Version V1.0
*Description:
*/
abstract class AbstractNoNameClass {

	//attributes and methods
    int age ;
    
    public void programming() {
    	System.out.println("programming");
    }
    
	abstract void sleeping();
	

	public static void main(String[] args) {
		// TODO Auto-generated method stub
        //Create and use on the spot
		AbstractNoNameClass a = new AbstractNoNameClass() {
			
			@Override
			void sleeping() {
				// TODO Auto-generated method stub
				System.out.println("sleeping");
			}
		};
		a.sleeping();
		
	}

}

Pay attention to the format of anonymous internal class. When creating the class, add a code block that rewrites the abstract method and put it in the terminator; Before.

Keywords: Java Back-end

Added by Abarak on Thu, 17 Feb 2022 11:30:10 +0200