Interface and inheritance

1, Interface

When designing LOL, there are two kinds of offensive heroes, one is to attack the physics department and the other is to attack the magic department

At this time, you can use the interface to achieve this effect.

The interface is like an agreement. We agree that some heroes are heroes of the physics department, so they must be able to carry out physical attacks.

Step 1: physical attack interface

Create an interface file - > New - > interface
AD declares a method physicAttack physical attack, but there is no method body. It is an "empty" method

package charactor;
 
public interface AD {
        //Physical injury
    public void physicAttack();
}

Step 2: design a class of heroes that can use physical attacks

Design a kind of hero that can use physical attack. This kind of hero is called AD in LOL
Class: ADHero
It inherits the Hero class, so it inherits the name,hp,armor and other attributes

Implementing an interface is equivalent to committing to a certain convention

Therefore, to implement the AD interface, you must provide the method physicAttack() declared in the AD interface
The implementation uses the keyword implements in syntax

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

Step 3: magic attack interface

Create an interface file - > New - > interface
AP declares a method magicAttack magic attack, but there is no method body. It is an "empty" method

package charactor;
 
public interface AP {
 
    public void magicAttack();
}

Step 4: design a class of heroes that can only use magic attacks

Design a kind of hero, which can only use magic attack. This kind of hero is called AP in LOL
Class: APHero
It inherits the Hero class, so it inherits the name,hp,armor and other attributes
At the same time, if you implement the AP interface, you must provide the method magicAttack() declared in the AP interface
The implementation uses the keyword implements in syntax

package charactor;
 
public class APHero extends Hero implements AP{
 
    @Override
    public void magicAttack() {
        System.out.println("Make a magic attack");
    }
 
}

Step 5: design a kind of hero that can use both physical attack and magic attack

A hero that can attack both physically and magically
Like ezrell, picturesque policewoman Caitlin

package charactor;
  
//A hero who can do both physical and magic damage
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");
    }
  
}

Step 6: under what circumstances are interfaces used

In the above example, it seems that the interface and not the interface are the same. What is the meaning of the interface

Learning a knowledge point is carried out from shallow to deep. Here, the concept of interface is just introduced. To truly understand the benefits of interface, we need more practice and extensive application in more complex systems before we can really understand it, such as learning polymorphic Then we can further deepen our understanding.

Just touching a concept, I hope to achieve a perfect learning effect. Such a learning goal is unscientific.

2, Object transformation

Example 1: clarify the concepts of reference type and object type

First, clarify the concepts of reference type and object type
In this example, there is an object new ADHero(), and there is also a reference ad
The object is typed and is ADHero
References are also typed. They are ADHero
In general, the reference type and object type are the same
The problem of type conversion to be discussed next refers to the conversion problem when the reference type and object type are inconsistent

package charactor;
 
public class Hero {
    public String name;
    protected float hp;
     
    public static void main(String[] args) {
         
        ADHero ad = new ADHero();
         
    }
}

Example 2: subclass to parent (upward transformation)

The so-called transformation means that type conversion is required only when the reference type and object type are inconsistent
Type conversions sometimes succeed and sometimes fail (Ref Type conversion of basic type)

Can the conversion succeed? Teach you a very simple way to judge
Use the one on the right as the one on the left. Does it make sense

Hero h = new Hero();

ADHero ad = new ADHero();

h = ad;

The type of object pointed to by the ad reference on the right is physical attack hero
The type referenced by h on the left is ordinary hero
Does it make sense to treat physical attack heroes as ordinary heroes? If it makes sense, you can turn

It makes sense to convert all subclasses into superclasses. Like the examples around you

Apple inherited the mobile phone as an ordinary mobile phone
Yibao purified water inherits the drink and uses Yibao purified water as a drink
Mr. Cang inherited the animals and took Mr. Cang as his teacher.

package charactor;
 
public class Hero {
    public String name;
    protected float hp;
     
    public static void main(String[] args) {
         
        Hero h = new Hero();
         
        ADHero ad = new ADHero();
         
        //Type conversion refers to converting the type of the object pointed to by one reference to the type of another reference
         
        //The type of the object to which the ad reference refers is ADHero
        //h refers to Hero
        //If you use ADHero as Hero, you can
         
        h = ad;
         
    }
}

Example 3: parent rotor class (transition down)

The parent class and rotor class are sometimes OK and sometimes not, so they must be cast.
Forced conversion means that there are risks in the conversion, and the risks are borne by yourself.

When will it work?

\1. Hero h =new Hero();

\2. ADHero ad = new ADHero();

\3. h = ad;

\4. ad = (ADHero) h;

The third line is to change the child class to the parent class. It must be OK
Line 4 is the parent rotor class, so the forced rotation is required.
The object pointed to by this reference is ADHero, so in line 4, ADHero will be converted to ADHero, and the conversion will be successful.

When can't I change?

\1. Hero h =new Hero();

\2. ADHero ad = new ADHero();

\3. Support s =new Support();

\4. h = s;

\5. ad = (ADHero)h;

Line 4 is the conversion from a child class to a parent class, which can be successfully converted
Line 5 is to convert the object Support pointed to by the h reference to the type ADHero of the ad reference. Semantically speaking, it doesn't make sense to use the physical attack hero as an auxiliary hero, so it will fail the forced conversion and throw abnormal

The following is a key line analysis of the complete code

Line 14: you can use ad as Hero
After conversion, the h reference points to an ad object
Line 15: the h reference may point to an ad object or a support object
Therefore, when converting h reference to AD type, it may succeed or fail
Therefore, forced conversion should be carried out, in other words, the consequences of conversion should be borne by itself
Whether the conversion is successful depends on what kind of object the reference h refers to
In this example, h refers to an ad object, so it is possible to convert it to ADHero type
Line 16: if you use a support object as a Hero, you can
After conversion, the h reference points to a support object
Line 17: at this time, h refers to a support object, so conversion to ADHero type will fail.
The manifestation of failure is to throw an exception ClassCastException type conversion exception

package charactor;
  
import charactor1.Support;
  
public class Hero {
    public String name;
    protected float hp;
      
    public static void main(String[] args) {
        Hero h =new Hero();
        ADHero ad = new ADHero();
        Support s =new Support();
          
        h = ad;
        ad = (ADHero) h;
        h = s;
        ad = (ADHero)h;
    }
      
}

Example 4: two classes without inheritance relationship are converted to each other

If two classes without inheritance relationship convert to each other, they will fail
Although both ADHero and APHero inherit Hero, they do not inherit each other
"Using magic heroes as physical heroes" doesn't make sense in semantics

package charactor;
 
public class Hero {
    public String name;
    protected float hp;
 
    public static void main(String[] args) {
        ADHero ad = new ADHero();
 
        APHero ap = new APHero();
 
        // Conversion between types without inheritance relationship is bound to fail, so compilation errors will occur
        ad = (ADHero) ap;
 
    }
 
}

Example 5: converting an implementation class to an interface (up conversion)

The object that refers to ad is the ADHero type, which implements the ad interface
Line 10: convert an ADHero type to an AD interface
Semantically speaking, an ADHero is used as an AD, while 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.

package charactor;
   
public class Hero {
    public String name;
    protected float hp;
       
    public static void main(String[] args) {
        ADHero ad = new ADHero();
          
        AD adi = ad;
          
    }
       
}

Example 6: converting an interface to an implementation class (downward transformation)

Line 10: the AD reference points to ADHero, while the adi reference is the interface type: ad. the implementation class is converted to an interface, which is an upward transformation, so there is no need for forced conversion, and it will succeed
Line 12: adi actually points to an ADHero, so it can be converted successfully
Line 14: the object pointed to by the adi reference is an ADHero, and it will fail to convert to an ADHero.

Assuming that the conversion is successful, the magicAttack method can be used, and the object ADHero pointed to by adi reference has no magicAttack method.

package charactor;
     
public class Hero {
    public String name;
    protected float hp;
         
    public static void main(String[] args) {
        ADHero ad = new ADHero();
            
        AD adi = ad;
   
        ADHero adHero = (ADHero) adi;
            
        ADAPHero adapHero = (ADAPHero) adi;
        adapHero.magicAttack();
    }
         
}

Example 7: instanceof

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

package charactor;
  
public class Hero {
    public String name;
    protected float hp;
      
    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 ADHero type
        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

Subclasses can inherit the object methods of the parent class

Providing this method repeatedly after inheritance is called method rewriting

Also called override

Step 1: parent Item

The parent Item has a method called effect

package property;
 
public class Item {
    String name;
    int price;
 
    public void buy(){
        System.out.println("purchase");
    }
    public void effect() {
        System.out.println("Items can be effective after use");
    }
 
}

Step 2: subclass lifeposition

package property;
 
public class LifePotion extends Item{
     
    public void effect(){
        System.out.println("After the blood bottle is used, it can return blood");
    }
     
}

Step 3: call the rewrite method

Call overridden method
The call will execute the overridden method, not the method from the parent class
Therefore, lifeposition's effect will print:
"After using the blood bottle, you can return blood"

package property;
 
public class Item {
    String name;
    int price;
     
    public void effect(){
        System.out.println("Items can be effective after use");
    }
     
    public static void main(String[] args) {
        Item i = new Item();
        i.effect();
         
        LifePotion lp =new LifePotion();
        lp.effect();
    }
     
}

Step 4: what if such a mechanism is not rewritten?

If such a mechanism is not overridden, that is, once the lifeposition class inherits the Item, all methods cannot be modified.

However, lifeposition hopes to provide some different functions. To achieve this goal, we can only give up inheriting Item, rewrite all properties and methods, and then make a small change when writing effect

This increases development time and maintenance costs

package property;
 
public class Item {
    String name;
    int price;
 
    public void buy(){
        System.out.println("purchase");
    }
    public void effect() {
        System.out.println("Items can be effective after use");
    }
 
}
package property;
 
public class LifePotion {
    String name;
    int price;
 
    public void buy(){
        System.out.println("purchase");
    }
    public void effect(){
        System.out.println("After the blood bottle is used, it can return blood");
    }
}

4, Polymorphism

Polymorphism of operators
+It can be used as an arithmetic operation or as a string connection

Class polymorphism
A parent class reference points to a child class object

Example 1: operator polymorphism

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

package charactor;
   
public class Hero {
    public String name;
    protected float hp;
 
    public static void main(String[] args) {
         
        int i = 5;
        int j = 6;
        int k = i+j; //If both sides of the + sign are integers, then + represents the addition of numbers
         
        System.out.println(k);
         
        int a = 5;
        String b = "5";
         
        String c = a+b; //If either side of the + sign is a string, then + represents a string connection
        System.out.println(c);
         
    }
       
}

Example 2: polymorphism condition of class

Polymorphism of observation class:
\1. Both I1 and i2 are Item types
\2. Both call the effect method
\3. Output different results

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

package property;
 
public class Item {
    String name;
    int price;
 
    public void buy(){
        System.out.println("purchase");
    }
    public void effect() {
        System.out.println("Items can be effective after use ");
    }
     
    public static void main(String[] args) {
        Item i1= new LifePotion();
        Item i2 = new MagicPotion();
        System.out.print("i1  yes Item Type, execution effect Print:");
        i1.effect();
        System.out.print("i2 Also Item Type, execution effect Print:");
        i2.effect();
    }
 
}
package property;
 
public class LifePotion extends Item {
    public void effect(){
        System.out.println("After the blood bottle is used, it can return blood");
    }
}
package property;
 
public class MagicPotion extends Item{
 
    public void effect(){
        System.out.println("After using the blue bottle, you can return to magic");
    }
}

Example 3: polymorphic conditions

To realize class polymorphism, the following conditions are required
\1. The parent class (Interface) reference points to the subclass object
\2. The methods called are rewrite
So what does polymorphism do? By comparison Do not use polymorphism And Use polymorphism To learn more

Example 4: polymorphism of a class - do not use polymorphism

If polymorphism is not used,
If the Hero wants to use blood bottle and magic bottle, he needs to design two methods for Hero
useLifePotion
useMagicPotion

In addition to blood bottles and magic bottles, there are many kinds of items, so you need to design many methods, such as
Usepurityposition purifying Potion
useGuard guard
Useinvisibleposition use invisible Potion
Wait, wait

package charactor;
 
import property.LifePotion;
import property.MagicPotion;
   
public class Hero {
    public String name;
    protected float hp;
 
    public void useLifePotion(LifePotion lp){
        lp.effect();
    }
    public void useMagicPotion(MagicPotion mp){
        mp.effect();
    }
 
    public static void main(String[] args) {
         
        Hero garen =  new Hero();
        garen.name = "Galen";
     
        LifePotion lp =new LifePotion();
        MagicPotion mp =new MagicPotion();
         
        garen.useLifePotion(lp);
        garen.useMagicPotion(mp);
         
    }
       
}

Example 5: polymorphism of classes - using polymorphism

If there are many kinds of items, many methods need to be designed
Such as useArmor,useWeapon, etc

At this time, polymorphism is used to solve this problem
Design a method called useItem whose parameter type is Item
If you are using a blood bottle, call this method
If you are using a magic bottle, call this method
No matter what items the hero wants to use, it only needs one method

package charactor;
 
import property.Item;
import property.LifePotion;
import property.MagicPotion;
   
public class Hero {
    public String name;
    protected float hp;
 
    public void useItem(Item i){
        i.effect();
    }
 
    public static void main(String[] args) {
         
        Hero garen =  new Hero();
        garen.name = "Galen";
     
        LifePotion lp =new LifePotion();
        MagicPotion mp =new MagicPotion();
         
        garen.useItem(lp);
        garen.useItem(mp);     
         
    }
       
}

5, Hide

Similar to overriding, overriding a method is an object method whose subclass overrides the parent class

Hiding means that the subclass overrides the class method of the parent class

Step 1: parent class

The parent class has a class method: battleWin

package charactor;
  
public class Hero {
    public String name;
    protected float hp;
  
    //Class method
    //You can call it directly through the class
    public static void battleWin(){
        System.out.println("hero battle win");
    }
      
}

Step 2: the subclass hides the class method of the parent class

Subclass hides the class method of the parent class

package charactor;
  
public class ADHero extends Hero implements AD{
  
    @Override
    public void physicAttack() {
        System.out.println("Physical attack");
    }
     
    //Hide the battleWin method of the parent class
    public static void battleWin(){
        System.out.println("ad hero battle win");
    }   
     
    public static void main(String[] args) {
        Hero.battleWin();
        ADHero.battleWin();
    }
  
}

6, super keyword

Step 1: prepare a parent class that explicitly provides a parameterless constructor

Prepare a parent class that explicitly provides a parameterless constructor
When instantiating the Hero object, its construction method will print
Construction method of "Hero"“

package charactor;
 
import property.Item;
 
public class Hero {
        
    String name; //full name
        
    float hp; //Blood volume
        
    float armor; //Armor
        
    int moveSpeed; //Moving speed
     
    public void useItem(Item i){
        System.out.println("hero use item");
        i.effect();
    }
     
    public Hero(){
        System.out.println("Hero Construction method of ");
    }
     
    public static void main(String[] args) {
        new Hero();
    }
      
}

Step 2: instantiate the subclass, and the construction method of the parent class will be called

The ADO method () will be instantiated to construct an ADO method
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

package charactor;
  
public class ADHero extends Hero implements AD{
  
    @Override
    public void physicAttack() {
        System.out.println("Physical attack");
    }
     
    public ADHero(){
         
        System.out.println("AD Hero Construction method of");
    }
     
    public static void main(String[] args) {
 
        new ADHero();
         
    }
  
}

Step 3: the parent class explicitly provides two construction methods

They are the construction method without parameters and the construction method with one parameter

package charactor;
 
import property.Item;
 
public class Hero {
        
    String name; //full name
        
    float hp; //Blood volume
        
    float armor; //Armor
        
    int moveSpeed; //Moving speed
     
    public void useItem(Item i){
        System.out.println("hero use item");
        i.effect();
    }   
     
    public Hero(){
        System.out.println("Hero Parameter free construction method of ");
    }
     
    public Hero(String name){
        System.out.println("Hero There is a parameter construction method ");
        this.name = name;
    }
     
    public static void main(String[] args) {
        new Hero();
    }
      
}

Step 4: the subclass explicitly calls the parent class construction method with parameters

Use the keyword super to explicitly call the constructor with parameters of the parent class

package charactor;
  
public class ADHero extends Hero implements AD{
  
    @Override
    public void physicAttack() {
        System.out.println("Physical attack");
    }
     
    public ADHero(String name){
        super(name);
        System.out.println("AD Hero Construction method of");
    }
     
    public static void main(String[] args) {
        new ADHero("Dreven");
    }
  
}

Step 5: call the parent class attribute

Call the moveSpeed attribute of the parent class through super
ADHero also provides the attribute moveSpeed

public int getMoveSpeed(){

return this.moveSpeed;

}

public int getMoveSpeed2(){

return super.moveSpeed;

}

package charactor;
  
public class ADHero extends Hero implements AD{
 
    int moveSpeed=400; //Moving speed
 
    @Override
    public void physicAttack() {
        System.out.println("Physical attack");
    }
     
    public int getMoveSpeed(){
        return this.moveSpeed;
    }
     
    public int getMoveSpeed2(){
        return super.moveSpeed;
    }
     
    public static void main(String[] args) {
        ADHero h= new ADHero();
         
        System.out.println(h.getMoveSpeed());
        System.out.println(h.getMoveSpeed2());
         
    }
  
}

Step 6: call the parent class method

ADHero overrides the useItem method and calls the useItem method of the parent class through super in useItem

package charactor;
 
import property.Item;
import property.LifePotion;
 
public class ADHero extends Hero implements AD {
 
    int moveSpeed = 400; // Moving speed
 
    @Override
    public void physicAttack() {
        System.out.println("Physical attack");
    }
 
    public int getMoveSpeed() {
        return this.moveSpeed;
    }
 
    public int getMoveSpeed2() {
        return super.moveSpeed;
    }
 
    // Overwrite useItem and invoke the userItem method of the parent class in middle note.
    public void useItem(Item i) {
        System.out.println("adhero use item");
        super.useItem(i);
    }
 
    public static void main(String[] args) {
        ADHero h = new ADHero();
 
        LifePotion lp = new LifePotion();
 
    }
 
}

7, Object class

The Object class is the parent of all classes

Step 1: the Object class is the parent of all classes

When declaring a class, it inherits Object by default
public class Hero extends Object

package charactor;
 
import property.Item;
 
public class Hero extends Object {
        
    String name; //full name
        
    float hp; //Blood volume
        
    float armor; //Armor
        
    int moveSpeed; //Moving speed
     
    public void useItem(Item i){
        System.out.println("hero use item");
        i.effect();
    }   
     
    public Hero(){
        System.out.println("Hero Parameter free construction method of ");
    }
     
    public Hero(String name){
        System.out.println("Hero There is a parameter construction method ");
        this.name = name;
    }
     
    public static void main(String[] args) {
        new Hero();
    }
      
}

Step 2: 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
Through system out. Println print object is to print the toString() return value of the object

package charactor;
  
public class Hero {
    public String name;
    protected float hp;
      
    public String toString(){
        return name;
    }
      
    public static void main(String[] args) {
         
        Hero h = new Hero();
        h.name = "Galen";
        System.out.println(h.toString());
        //To print an object directly is to print the toString() return value of the object
        System.out.println(h);
    }
}

Step 3: 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.

finalize() is not a method actively called by the developer, but by the virtual machine JVM.

package charactor;
  
public class Hero {
    public String name;
    protected float hp;
      
    public String toString(){
        return name;
    }
     
    public void finalize(){
        System.out.println("The hero is being recycled");
    }
      
    public static void main(String[] args) {
        //Only one reference
        Hero h;
        for (int i = 0; i < 100000; i++) {
            //Constantly generate new objects
            //Every time an object is created, there is no reference to the previous object
            //Those objects meet the conditions of garbage collection
            //When there is a large amount of garbage, garbage collection will be triggered
            //Once the object is recycled, its finalize() method is called
            h = new Hero();
        }
 
    }
}

Step 4: equals()

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

Suppose that when two heroes have the same hp, we think they are the same

package charactor;
  
public class Hero {
    public String name;
    protected float hp;
      
    public boolean equals(Object o){
        if(o instanceof Hero){
            Hero h = (Hero) o;
            return this.hp == h.hp;
        }
        return false;
    }
      
    public static void main(String[] args) {
        Hero h1= new Hero();
        h1.hp = 300;
        Hero h2= new Hero();
        h2.hp = 400;
        Hero h3= new Hero();
        h3.hp = 300;
         
        System.out.println(h1.equals(h2));
        System.out.println(h1.equals(h3));
    }
}

Step 5:==

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

package charactor;
  
public class Hero {
    public String name;
    protected float hp;
      
    public boolean equals(Object o){
        if(o instanceof Hero){
            Hero h = (Hero) o;
            return this.hp == h.hp;
        }
        return false;
    }
      
    public static void main(String[] args) {
        Hero h1= new Hero();
        h1.hp = 300;
        Hero h2= new Hero();
        h2.hp = 400;
        Hero h3= new Hero();
        h3.hp = 300;
         
        System.out.println(h1==h2);
        System.out.println(h1==h3);
         
    }
}

Step 6:hashCode()

The hashCode method returns the hash value of an object, but it is meaningless to explain this method before understanding the meaning of the hash value.

The meaning of hashCode will be put in hashcode principle Chapter explanation

Step 7: thread synchronization related methods

Object also provides methods related to thread synchronization
wait()
notify()
notifyAll()
The understanding of this part needs to be based on a sufficient understanding of thread safety, so it will be placed in Thread interaction Chapter explanation

Step 8: getClass()

getClass() will return the name of an object Class object , which belongs to advanced content, and is not suitable for beginners to contact too early. For details about class objects, please refer to Reflection mechanism

8, final keyword

final modifies classes, methods, basic types and variables, which have different meanings when referenced.

Example 1: final modifier class

When Hero is modified to final, it means that Hero cannot be inherited
Compilation errors will occur in its subclasses

package charactor;
 
public final class Hero extends Object {
        
    String name; //full name
        
    float hp; //Blood volume
        
}

Example 2: final modification method

If the useItem method of Hero is modified to final, the method cannot be overridden in ADHero

package charactor;
 
import property.Item;
 
public class Hero extends Object {
        
    String name; //full name
        
    float hp; //Blood volume
        
    float armor; //Armor
        
    int moveSpeed; //Moving speed
     
    public final void useItem(Item i){
        System.out.println("hero use item");
        i.effect();
    }   
     
    public Hero(){
        System.out.println("Hero Parameter free construction method of ");
    }
     
    public Hero(String name){
        System.out.println("Hero There is a parameter construction method ");
        this.name = name;
    }
     
    public static void main(String[] args) {
        new Hero();
    }
      
}

Example 3: final modifies basic type variables

final modifies a basic type variable, indicating that the variable has only one assignment opportunity
Line 16 is assigned, and line 17 can no longer be assigned

package charactor;
 
public class Hero extends Object {
        
    String name; //full name
        
    float hp; //Blood volume
        
    float armor; //Armor
        
    int moveSpeed; //Moving speed
     
    public static void main(String[] args) {
 
        final int hp;
        hp = 5;
        hp = 6;
         
    }
}

Example 4: final modifier reference

final modifier reference
The h reference is modified to final, which means that the reference has only one chance to point to the object
So there will be a compilation error on line 17
However, the attribute value hp of the object is still modified through h reference, because hp does not have final decoration

package charactor;
 
public class Hero extends Object {
        
    String name; //full name
        
    float hp; //Blood volume
        
    float armor; //Armor
        
    int moveSpeed; //Moving speed
     
    public static void main(String[] args) {
 
        final Hero h;
        h  =new Hero();
        h  =new Hero();
         
        h.hp = 5;
         
    }
      
}

Example 5: constants

Constants refer to values that can be exposed, accessed directly, and do not change
For example, the number of itemTotalNumber items is 6

package charactor;
 
public class Hero extends Object {
     
    public static final int itemTotalNumber = 6;//Number of item columns
        
    String name; //full name
        
    float hp; //Blood volume
        
    float armor; //Armor
        
    int moveSpeed; //Moving speed
     
    public static void main(String[] args) {
 
        final Hero h;
        h  =new Hero();
         
        h.hp = 5;
         
    }
      
}

9, 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 and uses the modifier "abstract"“

When a class has abstract methods, the class must be declared as an abstract class

#### Step 1: abstract class

Add an abstract method attack for Hero, and declare Hero as abstract.
Aphero, adhero, and adhero are subclasses of Hero and inherit the attributes and methods of Hero.
However, their attack methods are different, so after inheriting the Hero class, these subclasses must provide different attack method implementations.

package charactor;
 
public abstract class Hero {
    String name;
 
    float hp;
 
    float armor;
 
    int moveSpeed;
 
    public static void main(String[] args) {
 
    }
 
    // Abstract method attack
    // Subclasses of Hero will be required to implement the attack method
    public abstract void attack();
 
}
package charactor;
 
public class ADHero extends Hero implements AD {
 
    public void physicAttack() {
        System.out.println("Physical attack");
    }
 
    @Override
    public void attack() {
        physicAttack();
    }
 
}
package charactor;
 
public class APHero extends Hero implements AP {
 
    @Override
    public void magicAttack() {
        System.out.println("Make a magic attack");
    }
 
    @Override
    public void attack() {
        magicAttack();
    }
 
}
package charactor;
 
public class ADAPHero extends Hero implements AD, AP {
 
    @Override
    public void attack() {
 
        System.out.println("You can attack both physically and magically");
    }
 
    public void magicAttack() {
        System.out.println("Make a magic attack");
    }
 
    public void physicAttack() {
        System.out.println("Physical attack");
    }
 
}

Step 2: abstract classes can have no abstract methods

Hero class 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

package charactor;
   
public abstract class Hero {
    String name;
          
    float hp;
          
    float armor;
          
    int moveSpeed;
       
    public static void main(String[] args) {
        //Although there is no abstract method, once it is declared as an abstract class, it cannot be instantiated directly
        Hero h= new Hero();
    }
          
}

Step 3: the difference between abstract classes and interfaces

Difference 1:
A subclass can only inherit one abstract class, not more than one
Subclasses can implement multiple interfaces
Difference 2:
Abstract classes can define
public,protected,package,private
Static and non static properties
final and non final Attributes
However, the attributes declared in the interface can only be
public
static state
final
Even without an explicit declaration
**
Note: * * both abstract classes and interfaces can have entity methods. Methods in interfaces are called Default method

package charactor;
  
public interface AP {
  
    public static final int resistPhysic = 100;
     
    //resistMagic is not explicitly declared as public static final
    //But it still defaults to public static final
    int resistMagic = 0;
     
    public void magicAttack();
}

10, Inner class

There are four internal classes:
Non static inner class
Static inner class
Anonymous class
Local class

Step 1: non static inner class

Non static internal class BattleScore "battle score"
Non static inner classes can be defined directly in a class

For example:
Combat achievements are meaningful only when a hero object exists
Therefore, when instantiating BattleScore, it must be based on an existing hero
Syntax: new external class () New inner class ()
As a non static internal class of Hero, you can directly access the private instance property name of the external class

package charactor;
 
public class Hero {
    private String name; // full name
 
    float hp; // Blood volume
 
    float armor; // Armor
 
    int moveSpeed; // Moving speed
 
    // 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 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();
    }
 
}

Step 2: static inner class

Declare a static inner class in a class
For example, when the enemy crystal has no blood, all your heroes win, not just a specific hero.
Unlike the non static inner class, the instantiation of the static inner class crystal class 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
Static inner classes are no different from ordinary classes except that they can access private static members of external classes

package charactor;
  
public 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 static void main(String[] args) {
        //Instantiate static inner class
        Hero.EnemyCrystal crystal = new Hero.EnemyCrystal();
        crystal.checkIfVictory();
    }
  
}

Step 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

package charactor;
   
public abstract class Hero {
    String name; //full name
          
    float hp; //Blood volume
          
    float armor; //Armor
          
    int moveSpeed; //Moving speed
      
    public abstract void attack();
      
    public static void main(String[] args) {
          
        ADHero adh=new ADHero();
        //By printing adh, you can see that the object adh belongs to ADHero class
        adh.attack();
        System.out.println(adh);
          
        Hero h = new Hero(){
            //Implement attack method on the spot
            public void attack() {
                System.out.println("New offensive means");
            }
        };
        h.attack();
        //By printing h, you can see that the object h belongs to Hero , a class name automatically assigned by the system
          
        System.out.println(h);
    }
      
}

Step 4: local classes

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

package charactor;
   
public abstract class Hero {
    String name; //full name
          
    float hp; //Blood volume
          
    float armor; //Armor
          
    int moveSpeed; //Moving speed
      
    public abstract void attack();
      
    public static void main(String[] args) {
          
        //The difference from anonymous classes is that local classes have custom class names
        class SomeHero extends Hero{
            public void attack() {
                System.out.println( name+ " New offensive means");
            }
        }
         
        SomeHero h  =new SomeHero();
        h.name ="Meepo ";
        h.attack();
    }
      
}

Step 5: use external local variables in anonymous classes

Use external local variables in anonymous classes. External local variables must be modified to final

Why should it be declared as final? Its mechanism is complex. Please refer to the explanation in the second Hero code

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

package charactor;
   
public abstract class Hero {
 
    public abstract void attack();
      
    public static void main(String[] args) {
 
        //Use external local variables in anonymous classes. External local variables must be modified to final
        final int damage = 5;
         
        Hero h = new Hero(){
            public void attack() {
                System.out.printf("New means of attack, resulting in%d Point damage",damage );
            }
        };
 
    }
      
}
package charactor;
   
public abstract class Hero {
 
    public abstract void attack();
      
    public static void main(String[] args) {
 
        //When using an external local variable in an anonymous class, damage must be modified to final
        int damage = 5;
         
        //Anonymous class uses anonymous mechanism to hide anonymous properties of anonymous class
         
        //In fact, an anonymous class will declare a damage attribute in the anonymous class, and use the constructor to initialize the value of the attribute
        //The damage used in the attack actually uses the internal damage, not the external damage
         
        //Assume that the external attribute does not need to be declared final
        //If you modify the value of damage in attack, it will be implied that you have modified the value of the external variable damage
         
        //But they are different variables, so it is impossible to modify the external variable damage
        //Therefore, in order to avoid misleading, the external damage must be declared as final, and "looks" cannot be modified
        class AnonymousHero extends Hero{
            int damage;
            public AnonymousHero(int damage){
                this.damage = damage;
            }
            public void attack() {
                damage = 10;
                System.out.printf("New means of attack, resulting in%d Point damage",this.damage );
            }
        }
         
        Hero h = new AnonymousHero(damage);
         
    }
      
}

11, Default method

Step 1: what is the 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

Mortal interface adds a default method rev, which has an implementation body and is declared as default

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

Step 2: why is there a default method

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

Tags: Java

Posted by examiz on Sun, 17 Apr 2022 14:32:38 +0930