day11 [final, permissions, inner classes]

day11 [final, permissions, inner classes]

Chapter One final key

1.1 Overview

final keywords represent the final and unchangeable content.

  • final: immutable. For modifying the class, method and variable
    • Categories: modified class can not be inherited.
    • Methods: The modified method can not be overridden.
    • Variables: modified variables can not be reassigned

1.2 Method

1. Modified class

Meaning: This class can not have any subclasses. (Eunuch category)

format:

public final class 类名称{
    // ......
}

Note: If a class is final, then the method in which all members can not be overwritten (because there is no sub-categories)

2. The method of modifying members

When the final keyword when used to modify a method, this method is the final method can not be overwritten

format:

修饰符 final 返回值类型 方法名称(参数列表){
     // 方法体
}

Precautions:

For classes, methods, for, abstract and final keyword can not be used, because the contradictions

public void Fu{
    public final void method(){
        System.out.println("父类方法执行~");
    }
}

public void Zi extends Fu{
     // 会发生报错
    @Override
    public void method(){
        System.out.println("重写父类方法~")
    }
}

3. The modified local variables

For the basic data types:

Immutable say is variable immutable [data]

First assignment, life change

public static void main(String[] args){
    final int num = 10;
     System.out.println(num);// 10
    // num = 20; 报错
}

For reference address value [Type] is immutable

// 定一个学生类
public class Student{
    private String name;
    public Student(){
        
    }
    public Student(String name){
        this.name = name;
    }
    public void setName(String name){
        this.name = name;
    }
    public String getName(){
        return name;
    }
}

public class Final{
    public static void main(String[] args){
        final Stundet stu = new Student("雷神");
         System.out.println(stu); // 雷神
        //错误写法,final的引用类型变量的地址值不可改变
        // stu = new Student("蛇女");
        // 但是方法可以调用
        stu.setName("金刚狼");
        System.out.println(stu);// 金刚狼
    }
}

4. modified member variable

After using the keyword final modification, this variable is unlikely to change.

Member variable initialization method, there are two, can only choose one:

  • Display initialization:

    public class User{
        final String USERNAME = "张三";
        private int age;
    }
  • Constructor to initialize

    public class User{
        final String USERNAME;
        private int age;
        public User(String username,int age){
            this.USERNAME = username;
            this.age = age;
        }
    }

    note:

    The modified final constant names, generally writing specifications, all letters are capitalized.

    For example:

    public class Person{
    
        private final String name/* = 雷神*/;
        public Person(){
            name = "蜘蛛侠";
        }
        public Person(String name){
            this.name = name;
        }
        public String getName(){
            return name;
        }
    
       // public void setName(String name){
          //  this.name = name;
        //}
    }

Chapter authority modifier

2.1 Overview

Providing access to four in java using different access rights, the modified content will have different access rights

  • public: public
  • protected: Protected
  • default: default (nothing to write)
  • private: private

The ability to access different permissions 2.2

public protected default (empty) private
In the same class [myself]
The same package (a subclass of class-independent) [My neighbor]
Subclass different packages of [my son]
Irrespective of class of different packages [stranger]

所以 public > protected > (defoult) > private

Suggest:

  • Member variables private, hidden details.
  • Constructor uses public, easy to create the object.
  • Members method uses public, easy call.

Without permission modifier is (default).

  1. External class: public / (default)
  2. Members of the inner class: pubic / protected / (default) / private
  3. Local inner class: nothing to write.

Chapter inner class

3.1 Overview

If the inside of a thing contains another thing, then this is inside a class contains another class.

For example: the relationship between the body and the relationship between the car and the engine of the heart

classification:

  1. Members of the inner class
  2. Partial inner classes (including anonymous inner classes)

Members of the inner class

Format: class defined in the outer class method.

Definition Format:

修饰符 class 外部类名称{
    修饰符 class 内部类名称{
        // ...
    }
    // ...
}

Note: the outer, free access to, the topical, the need for internal class object.

Use internal class format

  1. Indirect use: in the process of the external class, inner classes, methods and the outer main class method calls.

  2. Direct method

    Formula: External Internal class name name = new class name of the object class name external () .new internal class name ();.

code show as below:

public class Body{// 外部类
    
    public class Heart{// 成员内部类
        
        // 内部类方法
        public void beat(){
        System.out.println("心脏跳动");
        System.out.println("我叫:"+name);
        }
    }
    
    //  外部类的成员变量
    private String name;
    
    // 外部类的方法
    public void methodBody{
         System.out.println("外部类的方法");
        new Heart().beat();
    }
    
    public String getName(){
        return name;
    }
    public void setName(String name){
        this.name = name
    }
}

Test categories:

public static void main(String[] args){
    // 外部类的对象
    Body body = new Body();
    // 通过外部类的对象,调用外部类的方法,里面间接在使用内部类Heart
    body.methodBody();
    
    // 按公式写
    Body.Heart heart = new Body().new Heart();
    heart.beat();
    
}

Variable inner classes access the same name

Access Format: External class name .this external class member variable name.

code show as below:

public class Outer {

    // 外部类的成员变量
    int num = 10;
    public class Inner{
        // 内部类的成员变量
        int num = 20;

        public void methodInter(){
            // 内部类的局部变量
            int num  = 30;
            System.out.println(num);// 局部变量  30
            System.out.println(this.num);// 内部变量 20
            System.out.println(Outer.this.num);// 外部类的成员变量 10


        }
    }
}

Test categories:

public class Demo02InnerClass {
    public static void main(String[] args) {
        Outer.Inner outer = new Outer().new Inner();
        outer.methodInter();
    }
}
//结果 30  20  10

Partial inner class

format:

修饰符 class 外部类名称{
    修饰符 返回值类型 外部类方法名称(参数列表){
        class 局部内部类{
            // 。。。。。
        }
    }
}

Local inner class final question

Local inner classes, local variables if you want to access, then the local variable must be a valid final [of].

Note: Starting from java 8+, the fact that as long as local variables constant, then the final keyword can be omitted.

the reason:

  1. new out of the objects in the heap memory of them.
  2. Local variables is the method followed in the stack memory.
  3. After the direction of the run, and immediately the stack, local variables will disappear immediately.
  4. But the new objects out of the heap among persist until the garbage collector disappear.

3.2 anonymous inner classes [focus]

premise

Anonymous inner class must inherit from a parent class or implement an interface

If the interface implementation class (parent class or subclass) requires only a single.

Conditions of Use

In this case it will be omitted the class definition, and instead use anonymous inner classes []

format

接口名称 对象名 = new 接口名称(){
    //覆盖从写所有抽象方法
};
对象名.方法名称调用
// 或
new 接口名称(){
    //覆盖从写所有抽象方法
}.方法名称调用;

Format Analysis:

  1. new representatives to create an object action
  2. Which interface is the interface name anonymous inner class needs to implement
  3. (...) This is what an anonymous inner class

Attention to the problem:

  1. Anonymous inner class, create an object when [], use only the only time.

    If you want to create an object several times, but the same type of content, there is no need to use an anonymous inner class

  2. Anonymous objects, invoke methods in [time], it can only be used only once.

    If you want the same object, call the method multiple times, you must give the object a name.

  3. Anonymous inner classes are omitted [implementation class / subclass name], but an anonymous object [object name omitted]

    He stressed: anonymous inner classes and anonymous object is not the same thing.

code show as below

interface:

public interface Face{
   public abstract void method();
}

Chong key anonymous inner classes and calls

public class Main{
    public void main(String[] args){
         // 格式一
    Face obj = new Face(){
        @Override
        public void method(){
            System.out.println("匿名内部类实现了方法~");
             }
         };
        obj.method();
        
        //  格式二
        new Face(){
        @Override
        public void method(){
            System.out.println("匿名内部类实现了方法~");
             }
         }.method();
        // 因为匿名对象无法调用第二次方法,如果有两个匿名内部类的话,需要在创建一个匿名内部类的匿名对象
        new Face(){
        @Override
        public void methodA(){
            System.out.println("匿名内部类A实现了方法~");
             }
         }.method();new Face(){
        @Override
        public void methodB(){
            System.out.println("匿名内部类B实现了方法~");
             }
         }.methodB();
    }
}

The fourth chapter reference type usage

4.1 class as a member variable

Custom game hero class

class Role{
    // 角色ID
    int id;
    // 生命值
    int blood;
    // 角色名称
    String name;
}

Use represented as an int id role and value of life, use of type String representing a name. In this case, String itself is a reference type, the use of

Similar to the way a constant, so it is often overlooked is the presence of a reference type. If we continue to enrich this class definition, to increase the Role of weapons, equipment and other property wear, how we write it?

The definition of weapon class that will increase attack capability:

class Weapon { 
    String name; // 武器名称 
        int hurt; // 伤害值 
}

Defined wear armor class, will increase defense capability, that is, to enhance the value of life:

class Armour {
    String name;// 装备名称
        int protect;// 防御值 
}

Defining roles categories:

class Role { 
    int id; 
        int blood;
        String name; // 添加武器属性
        Weapon wp; // 添加盔甲属性
        Armour ar; 
        // 提供get/set方法
        public Weapon getWp() {
        return wp; 
    }
    public void setWeapon(Weapon wp) { 
        this.wp = wp;
    }
    public Armour getArmour() {
        return ar; 
    }
    public void setArmour(Armour ar) { 
        this.ar = ar; 
    }
    // 攻击方法
    public void attack(){
        System.out.println("使用"+ wp.getName() +", 造成"+wp.getHurt()+"点伤害"); }
    // 穿戴盔甲
    public void wear(){ 
        // 增加防御,就是增加blood值
        this.blood += ar.getProtect(); 
        System.out.println("穿上"+ar.getName()+", 生命值增加"+ar.getProtect());
    }
}

Test categories:

public class Test {
    public static void main(String[] args) { 
        // 创建Weapon 对象
        Weapon wp = new Weapon("屠龙刀" , 999999); 
        // 创建Armour 对象
        Armour ar = new Armour("麒麟甲",10000);
        // 创建Role 对象
        Role r = new Role();
        // 设置武器属性
        r.setWeapon(wp); 
        // 设置盔甲属性
        r.setArmour(ar); 
        // 攻击
        r.attack(); 
        // 穿戴盔甲 
        r.wear();
    } 
}
输出结果: 
使用屠龙刀,造成999999点伤害
穿上麒麟甲 ,生命值增加10000

When the class as a member variable, it assignment operation, in fact, it is assigned to an object class.

4.2 interface as a member variable

Interface is a method of packaging for the corresponding game, the skills can be seen as extensions of game characters. So, if you want to expand more powerful skills, we in Role, the interfaces can be added as a member variable, a different set of skills.

Definition of the interface:

// 法术攻击
public interface FaShuSkill {
    public abstract void faShuAttack(); }

Defining roles categories:

public class Role {
    FaShuSkill fs;
    public void setFaShuSkill(FaShuSkill fs) {
        this.fs = fs; 
    }
    // 法术攻击 
    public void faShuSkillAttack(){ 
        System.out.print("发动法术攻击:");
        fs.faShuAttack(); 
        System.out.println("攻击完毕");
    } 
}

Define the test class:

public class Test {
    public static void main(String[] args) {
        // 创建游戏角色
        Role role = new Role();
        // 设置角色法术技能 
        role.setFaShuSkill(new FaShuSkill() {
            @Override
            public void faShuAttack() {
                System.out.println("纵横天下");
            }
        }); 
        // 发动法术攻击 
        role.faShuSkillAttack();
        // 更换技能 
        role.setFaShuSkill(new FaShuSkill() {
            @Override 
            public void faShuAttack() {
                System.out.println("逆转乾坤"); 
            }
        });
        // 发动法术攻击 
        role.faShuSkillAttack();
    } 
}
输出结果: 
发动法术攻击:纵横天下
攻击完毕 
发动法术攻击:逆转乾坤
攻击完毕

We use an interface as a member variable to change at any skill, this design is more flexible, enhancing the scalability of the program.

Interface as a member variable, it assignment operation, in fact, it is a subclass object assigned to the interface

4.3 interface method return type and argument as

public class DemoInterface {

    public static void main(String[] args) {
        // 左边接口名称,右边实现类名称   多态写法
        List<String> list = new ArrayList<>();

        List<String> result = addName(list);
        for (int i = 0; i < result.size(); i++) {
            System.out.println(result.get(i));
        }
    }
    public static List<String> addName(List<String> list){
        list.add("雷神");
        list.add("火麒麟");
        return list;
    }
}

Interface as a parameter, passing it the subclass object.

Interface type as the return value, to return to its subclass object

Guess you like

Origin www.cnblogs.com/anke-z/p/12444754.html