Java basic review-inner class

There are four internal categories:

  1. Non-static inner class
  2. Static inner class
  3. Anonymous class
  4. Local class

Non-static inner class

Non-static inner class BattleScore "Battle Score"
non-static inner class can be directly defined in a class

For example,
battle scores 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 internal class() is
the non-static of Hero The inner class can directly access the private instance attribute name of the outer class

package charactor;
 
public class Hero {
    private String name; // 姓名
 
    float hp; // 血量
 
    float armor; // 护甲
 
    int moveSpeed; // 移动速度
 
    // 非静态内部类,只有一个外部类对象存在的时候,才有意义
    // 战斗成绩只有在一个英雄对象存在的时候才有意义
    class BattleScore {
        int kill;
        int die;
        int assit;
 
        public void legendary() {
            if (kill >= 8)
                System.out.println(name + "超神!");
            else
                System.out.println(name + "尚未超神!");
        }
    }
 
    public static void main(String[] args) {
        Hero garen = new Hero();
        garen.name = "盖伦";
        // 实例化内部类
        // BattleScore对象只有在一个英雄对象存在的时候才有意义
        // 所以其实例化必须建立在一个外部类对象的基础之上
        BattleScore score = garen.new BattleScore();
        score.kill = 9;
        score.legendary();
    }
 
}

Static inner class

Declare a static internal class in a class,
such as the enemy crystal. When the enemy crystal has no blood, all your heroes win, not just a specific hero wins.
And nonstatic inner classes, static inner class instance of the class of the crystal does not require an instance of the class on the basis of external , may be directly instantiated
Syntax: new new class internal static type external ();.
Since there is no instance of a class of external, so In the static inner class, you cannot access the instance properties and methods of the
outer class. Except for the private static members of the outer class, there is no big difference between the static inner class and the ordinary class.

package charactor;
  
public class Hero {
    public String name;
    protected float hp;
  
    private static void battleWin(){
        System.out.println("battle win");
    }
     
    //敌方的水晶
    static class EnemyCrystal{
        int hp=5000;
         
        //如果水晶的血量为0,则宣布胜利
        public void checkIfVictory(){
            if(hp==0){
                Hero.battleWin();
                 
                //静态内部类不能直接访问外部类的对象属性
                System.out.println(name + " win this game");
            }
        }
    }
     
    public static void main(String[] args) {
        //实例化静态内部类
        Hero.EnemyCrystal crystal = new Hero.EnemyCrystal();
        crystal.checkIfVictory();
    }
  
}

Anonymous class

Anonymous class refers to instantiating a class while declaring it, making the code more concise and concise.
Generally, to use an interface or abstract class, you must create a subclass

Sometimes, for quick use, an abstract class is instantiated directly and its abstract method is implemented "on the spot".
Now that 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; //姓名
          
    float hp; //血量
          
    float armor; //护甲
          
    int moveSpeed; //移动速度
      
    public abstract void attack();
      
    public static void main(String[] args) {
          
        ADHero adh=new ADHero();
        //通过打印adh,可以看到adh这个对象属于ADHero类
        adh.attack();
        System.out.println(adh);
          
        Hero h = new Hero(){
            //当场实现attack方法
            public void attack() {
                System.out.println("新的进攻手段");
            }
        };
        h.attack();
        //通过打印h,可以看到h这个对象属于Hero$1这么一个系统自动分配的类名
          
        System.out.println(h);
    }
      
}

Local class

A local class can be understood as a named anonymous class
. The difference between an inner class and an anonymous class is that the inner class must be declared in the position of the member, that is, the position equal to the attribute and method.
The local class is the same as the anonymous class, declared directly in the code block, can be the main method, in the for loop, etc.

package charactor;
   
public abstract class Hero {
    String name; //姓名
          
    float hp; //血量
          
    float armor; //护甲
          
    int moveSpeed; //移动速度
      
    public abstract void attack();
      
    public static void main(String[] args) {
          
        //与匿名类的区别在于,本地类有了自定义的类名
        class SomeHero extends Hero{
            public void attack() {
                System.out.println( name+ " 新的进攻手段");
            }
        }
         
        SomeHero h  =new SomeHero();
        h.name ="地卜师";
        h.attack();
    }
      
}

Use external local variables in anonymous classes

Use external local variables in anonymous classes, and external local variables must be modified as final

Why declare as final? Its mechanism is more complicated, please refer to the explanation in the second Hero code

Note: In jdk8, it is no longer necessary to compulsorily modify to final. If final is not written, no error will be reported, because the compiler secretly adds invisible final to you

package charactor;
   
public abstract class Hero {
 
    public abstract void attack();
      
    public static void main(String[] args) {
 
        //在匿名类中使用外部的局部变量,外部的局部变量必须修饰为final
        final int damage = 5;
         
        Hero h = new Hero(){
            public void attack() {
                System.out.printf("新的进攻手段,造成%d点伤害",damage );
            }
        };
 
    }
      
}

(Final must be added, so it actually tells us that external variables cannot be modified in internal classes)

package charactor;
   
public abstract class Hero {
 
    public abstract void attack();
      
    public static void main(String[] args) {
 
        //在匿名类中使用外部的局部变量damage 必须修饰为final
        int damage = 5;
         
        //这里使用本地类AnonymousHero来模拟匿名类的隐藏属性机制
         
        //事实上的匿名类,会在匿名类里声明一个damage属性,并且使用构造方法初始化该属性的值
        //在attack中使用的damage,真正使用的是这个内部damage,而非外部damage
         
        //假设外部属性不需要声明为final
        //那么在attack中修改damage的值,就会被暗示为修改了外部变量damage的值
         
        //但是他们俩是不同的变量,是不可能修改外部变量damage的
        //所以为了避免产生误导,外部的damage必须声明为final,"看上去"就不能修改了
        class AnonymousHero extends Hero{
            int damage;
            public AnonymousHero(int damage){
                this.damage = damage;
            }
            public void attack() {
                damage = 10;
                System.out.printf("新的进攻手段,造成%d点伤害",this.damage );
            }
        }
         
        Hero h = new AnonymousHero(damage);
         
    }
      
}

Guess you like

Origin blog.csdn.net/xiaohaigary/article/details/89361360