JAVA learning notes (Chapter 5 interface and inheritance)

Posted by jrschwartz on Thu, 13 Jan 2022 14:00:17 +0100

1, What is an interface

An interface is like a template. There are methods without content in the interface. If a class uses an interface, it must declare the methods in the interface. Let's continue to take LOL games as an example:

Some heroes of LOL can use physical attack, some can use magic attack, and some can use both attacks. Therefore, heroes can be divided into ADHero, APHero and ADHero. They inherit the Hero class and the attributes such as name, HP and armor.

Taking physical attack as an example, declare a method physicAttack, which is in both ADHero class and ADHero class. One method is to define physicAttack method in ADHero class, and then ADHero class inherits ADHero class; Another way is to use interfaces. (why use interfaces instead of inheritance all the time? I'll add it later)

Define an AD interface, which provides a physicAttack() method, but there is no method body. It is an "empty" method.

interface AD {
    public void physicAttack();//Physical attack
}

The ADHero class implements the ad interface, uses the keyword {implements (which is similar to inheriting extensions), and must declare the methods in AD.

public class ADHero extends Hero implements AD{
 
    @Override
    public void physicAttack() {
        System.out.println("Physical attack");
    } 
}

Similarly, we can create AP interfaces, and the ADAPHero class implements AD and AP interfaces at the same time.

public class ADAPHero extends Hero implements AD,AP{
  
    @Override
    public void magicAttack() {
        System.out.println("Make a magic attack");
    }
  
    @Override
    public void physicAttack() {
        System.out.println("Physical attack");
    }  
}

2, Object transformation

1. Reference type? Object type?

public class MAIN {   
    public static void main(String[] args) {        
        ADHero ad = new ADHero();  
        Hero h = new ADHero();       
    }
}

Through the previous study, we can know that the first object is ADHero(), the reference is ad, and its type is ADHero (generally, the reference type and object type are the same); The second object is ADHero(), the reference is h, the object type is ADHero, and the reference type is Hero.

When the reference and object types are different, only the methods in the reference type can be used, that is, h only the methods in Hero can be used, but the methods added in ADHero cannot.

2. Type conversion

(1) Class to class conversion

Similar to the basic type conversion, the child class can be converted to the parent class automatically, while the parent class needs to be forcibly converted, but at its own risk (very simple, AD heroes are heroes, and heroes may not necessarily be AD heroes). Of course, two classes without inheritance will fail if they convert to each other.

 

However, h still cannot use the method in ADHero() after the conversion.

(2) Conversion between class and interface

The object that refers to ad is the ADHero type, which implements the ad interface. Semantically speaking, an ADHero is used as an ad, and the ad interface has only one physicAttack method, which means that the physicAttack method may be called after the conversion, and ADHero must have a physicAttack method, so the conversion can be successful. (that is, the class interface must be OK)

public static void main(String[] args) {
    ADHero ad = new ADHero();          
    AD adi = ad;
}

Line 4: adi actually points to an ADHero, so it can be converted successfully.
Line 5: the object pointed to by the adi reference is an ADHero. If you want to convert it to an ADHero, it will fail.     

public static void main(String[] args) {
    ADHero ad = new ADHero();            
    AD adi = ad;   
    ADHero adHero = (ADHero) adi;            
    ADAPHero adapHero = (ADAPHero) adi;
    adapHero.magicAttack();
}

3.  instanceof   

Judge whether the object pointed to by a reference is a Hero type or a subclass of Hero

public static void main(String[] args) {
    ADHero ad = new ADHero();
    APHero ap = new APHero();
         
    Hero h1= ad;
    Hero h2= ap;
         
    //Judge whether the object pointed to by reference h1 is of type ADHero
    System.out.println(h1 instanceof ADHero);
         
    //Judge whether the object pointed to by reference h2 is of APHero type
    System.out.println(h2 instanceof APHero);
         
    //Judge whether the object pointed to by reference h1 is a subtype of Hero
    System.out.println(h1 instanceof Hero);
}

3, Rewrite

Rewriting is very simple, that is, the subclass uses the methods of the parent class, but the subclass wants to make some changes. For example, the Hero class has the attack() method, which produces the effect of attacking, while ADHero also has the attack(), but the effect is to attack AD.

class Hero {
    public void attack() {
        System.out.println(" An attack was carried out");
    }
}
class ADHero extends Hero {
    public void attack() {
        System.out.println(" Once AD attack");
    }
}

It is conceivable that if such a mechanism is not overridden, once the subclass inherits the parent class, all methods can not be modified. However, subclasses want to provide a little different functions. In order to achieve this goal, they can only give up inheriting the parent class, rewrite all properties and methods, and then make a small change when writing the effect, which increases the development time and maintenance cost.

4, Polymorphism

Polymorphism: all of them are of the same type and call the same method, but they can present different states.

1. Polymorphism of operators

The same operator has different functions in different situations
If both sides of the + sign are integers, then + represents the addition of numbers
If either side of the + sign is a string, then + represents a string connection

2. Polymorphism condition of class

To realize class polymorphism, the following conditions are required

        1. A parent class (Interface) reference points to a child class object

        2. The method called has overrides

5, Hide

Similar to overriding, method overriding is an object method whose subclass overrides the parent class; Hiding means that the subclass overrides the class method of the parent class.

Class methods are static methods.

6, super keyword

1. Instantiate a subclass, and the constructor of the parent class will be called

Instantiate an ADHero(), and its constructor will be called
The constructor of its parent class will also be called
And the parent class constructor is called first
The subclass constructor will call the parameterless constructor of the parent class by default

 2. The usage of super is very similar to this. Super is the method that calls the parent class, while this calls its own.         

7, final modifier

1. The class modified by final cannot be inherited;

2. The method of inal modification cannot be rewritten;

3.final modifies a basic type variable, indicating that the variable has only one assignment opportunity;

Constants refer to values that can be exposed, accessed directly, and do not change

4.final modifies a reference, indicating that the reference has only one chance to point to the object.

8, object class

Object class is the parent class of all classes. When declaring a class, it inherits object by default.

1.toString()

The Object class provides a toString method, so all classes have toString methods. toString() means to return the string representation of the current Object.

2.finalize()

When an object has no reference to it, it meets the garbage collection condition. When it is garbage collected, its finalize() method is called.

3. equals()

equals() is used to determine whether the contents of two objects are the same.

4.==

This is not an Object method, but it is used to determine whether two objects are the same. More precisely, it is used to judge whether two references point to the same Object.

5.hashCode()

The hashCode method returns the hash value of an object.

6.Object also provides methods related to thread synchronization

7.getClass()

getClass() returns the class object of an object.

9, Abstract class

1. Abstract class

Declare a method in the class. This method has no implementation body and is an "empty" method;
Such a method is called an abstract method, using the modifier "abstract";
When a class has abstract methods, the class must be declared as an abstract class.

public abstract class Hero { 
    // Abstract method attack
    // Subclasses of Hero will be required to implement the attack method
    public abstract void attack();
 
}

It can be declared as an abstract class without providing abstract methods.

Once a class is declared as an abstract class, it cannot be instantiated directly.

2. Differences between abstract classes and interfaces

(1) Difference 1:
A subclass can inherit only one abstract class, not more than one
Subclasses can implement multiple interfaces
(2) Difference 2:
Abstract classes can define: public,protected,package,private, static and non static attributes, final and non final attributes
However, the attributes declared in the interface can only be public, static and final, even if there is no explicit declaration

Note: abstract classes and interfaces can have entity methods. The entity method in the interface is called the default method.

3. Default method

The default method is a new feature of JDK8, which means that the interface can also provide concrete methods, unlike before, it can only provide abstract methods. For example, the Mortal interface adds a default method {revise, which has an implementation body and is declared as default.

interface Mortal {
	public void die();
	default public void revive() {
		System.out.println("The hero is resurrected");
	}
}

Assuming that there is no default method mechanism, if you want to add a new method revive for Mortal, all classes that implement the Mortal interface need to be changed.
However, after the default method is introduced, the original class does not need to be changed, and the default method can be obtained.
By this means, we can well extend the new class without affecting the original class.

10, Inner class

1. Non static internal class

Non static inner classes can be defined directly in a class.

Syntax: new external class () New inner class ().

As a non static internal class, you can directly access the private instance property of the external class.

class Hero {
	private String name; // full name

	// Non static internal classes are meaningful only when an external class object exists
	// Combat achievements are meaningful only when a hero object exists
	class BattleScore {
		int kill;
		int die;
		int assit;

		public void legendary() {
			if (kill >= 8)
				System.out.println(name + "Holy shit(dota), legendary(lol)!");
			else
				System.out.println(name + "Not yet supernatural!");
		}
	}
}	

public class MAIN {
    public static void main(String[] args) {
		Hero garen = new Hero();
		garen.name = "Galen";
		// Instantiate inner class
		// The BattleScore object is meaningful only when a hero object exists
		// Therefore, its instantiation must be based on an external class object
		BattleScore score = garen.new BattleScore();
		score.kill = 9;
		score.legendary();
	}
}

2. Static internal class

Unlike non static internal classes, the instantiation of static internal classes does not need to be based on the instance of an external class, and can be instantiated directly
Syntax: new external class Static inner class ();
Because there is no instance of an external class, the instance properties and methods of an external class cannot be accessed in a static internal class;
Except that you can access private static members of external classes, static internal classes are no different from ordinary classes.

class Hero {
    public String name;
    protected float hp;
  
    private static void battleWin(){
        System.out.println("battle win");
    }
     
    //Enemy crystal
    static class EnemyCrystal{
        int hp=5000;         
        //If the health of the crystal is 0, declare victory
        public void checkIfVictory(){
            if(hp==0){
                Hero.battleWin();               
                //Static inner classes cannot directly access object properties of outer classes
                System.out.println(name + " win this game");
            }
        }
    }       
}

public class MAIN {
    public static void main(String[] args) {
        //Instantiate static inner class
        Hero.EnemyCrystal crystal = new Hero.EnemyCrystal();
        crystal.checkIfVictory();
    }
}

3. Anonymous class

Anonymous class refers to instantiating a class while declaring it, which makes the code more concise and concise;
Usually, to use an interface or abstract class, you must create a subclass;
Sometimes, in order to use it quickly, an abstract class is instantiated directly and its abstract methods are implemented "on the spot". Since the abstract method is implemented, it is a new class, but this class is not named. Such classes are called anonymous classes.

abstract class Hero {
    String name; //full name          
    float hp; //Blood volume          
    float armor; //Armor          
    int moveSpeed; //Moving speed
      
    public abstract void attack();
}
public abstract class Hero {
    public static void main(String[] args) {                   
        Hero h = new Hero(){
            //Implement attack method on the spot
            public void attack() {
                System.out.println("New means of attack");
            }
        };
        h.attack();         
        System.out.println(h);
    }
}

Use external local variables in anonymous classes. External local variables must be modified to final.
Note: in jdk8, there is no need to modify it to final. If you don't write final, you won't report an error, because the compiler secretly adds the invisible final for you.

4. Local class

A local class can be understood as an anonymous class with a name.
Unlike anonymous classes, inner classes must be declared in the position of members, that is, in an equal position with properties and methods. Like anonymous classes, local classes are directly declared in the code block, which can be the main method, for loop and so on.

abstract class Hero {
    String name; //full name          
    float hp; //Blood volume          
    float armor; //Armor          
    int moveSpeed; //Moving speed
      
    public abstract void attack();
}
public abstract class Hero {
    public static void main(String[] args) {                   
        class SomeHero extends Hero{
            public void attack() {
                System.out.println( name+ " New means of attack");
            }
        }   
        SomeHero h  =new SomeHero();
        h.name ="Meepo ";
        h.attack();
    }
}

Topics: Java Back-end