Java object oriented (inner class)

Posted by VanPEP on Sat, 04 Dec 2021 05:08:53 +0100

summary

If the interior of a thing contains another thing, then this is that a class contains another class.
For example, the relationship between the body and the heart. Another example: the relationship between automobile and engine.

Classification:
1. Member internal class
2. Local inner classes (including anonymous inner classes)

Definition format of member inner class:
Modifier class external class name{
    Modifier class inner class name{
        // ...
    }
    // ...
}

Note: for internal use and external use, you can access it at will; for external use and internal use, you need internal class objects.

==========================

Member inner class
How to use member inner classes? There are two ways:
1. Indirect method: use the internal class among the methods of the external class; then main just calls the methods of the external class.
2. Direct method, formula:
Class name object name = new class name ();
[external class name. Internal class name object name = new external class name (). New internal class name ();]

Upper code

Define an inner class in an outer class

public class Body {//External class
    public class Heart{//Member inner class
        //Methods of inner classes
        public void beat(){
            System.out.println("I am the method of the inner class");
            //Member variables in the external class can be called directly in the internal class of the member
            System.out.println("My name is"+name);
            System.out.println("My name is"+getName());
        }
    }
    private String name;//Member method (external class)

    public Body() {//Empty parameter
    }

    public Body(String name) {//Argument
        this.name = name;
    }
    //Methods of external classes
    public void method(){
        System.out.println("External class method");
        //You can create internal class objects in external classes and call internal class methods
//        Heart heart = new Heart();
//        heart.beat();
        //Or it can be called directly from an anonymous object
        new Heart().beat();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

test

public class Demo01InnerClass {
    public static void main(String[] args) {
        //Use member inner classes:
        //1. Indirect method: use the inner class through the outer class method
        Body body = new Body();
        body.method();
        System.out.println("=============");
        //2. Direct method: Formula: [external class name. Internal class name object name = new external class name (). New internal class name ();]
        Body.Heart bh = new Body().new Heart();
        bh.beat();
    }
}

Variable access with the same name of the inner class

Create class

//Accessing external class member variables in internal class methods: external class name. this. External class member variables
public class Outer {
    int age = 10;//External class member variable
    public class inter{
        int age = 20;//Internal class member variable
        public void methodAge(){//Inner class member method
            int age = 30;//Internal class local variable
            System.out.println(age);//Accessing local variables
            System.out.println(this.age);//Accessing internal class member variables
            System.out.println(Outer.this.age);//Accessing external class member variables
        }

    }
}

Test class

public class Demo02InterClass {
    public static void main(String[] args) {
        //Use inner classes
        Outer.inter oi = new Outer().new inter();
        oi.methodAge();
    }
}

Local inner class

If a class is defined inside a method, it is a local inner class.
"Local": only the current method can use it. It cannot be used outside this method.

Define format:
Modifier class external class name{
    Modifier return value type external class method name (parameter list){
        Class local inner class name{
            // ...
        }
    }
}

This section describes the permission modifiers of the following classes:
public > protected > (default) > private
 When defining a class, permission modifier rules:
1. External class: public / (default)
2. Member internal class: public / protected / (default) / private
 3. Local internal class: nothing can be written

Code:

Create a local inner class:

public class Outer {
    public void methodOuter(){
        //Local inner classes are defined in methods
        System.out.println("External class method");
        class Inter{
            int age = 20;
            public void methodInter(){
                System.out.println("Local inner class method"+age);
            }
        }
        //Local inner classes create objects in methods and call methods
        Inter inter = new Inter();
        inter.methodInter();
    }
}

Test class

public class DemoMain {
    public static void main(String[] args) {
        Outer outer = new Outer();
        outer.methodOuter();
    }
}

final problem of local inner class

Create class

public class MyOuter {
    int age = 20;//final is OK without writing, but the value of external member variable cannot be easily used by internal classes
//    final int age = 20;
    public void methodMyOuter(){
        class MyInter{
            public void methodMyInter(){
                System.out.println(age);//Member methods of external classes can be accessed in local inner classes
            }
        }
        MyInter myinter = new MyInter();
        myinter.methodMyInter();
    }
}

Test class

public class Test {
    public static void main(String[] args) {
        MyOuter o = new MyOuter();
        o.methodMyOuter();
    }
}

Anonymous internal class [key]

If the implementation class of the interface (or the subclass of the parent class) only needs to be used once,
In this case, you can omit the definition of this class and use anonymous inner class instead.

Definition format of anonymous inner class:
Interface name object name = new interface name (){
    //Override all abstract methods
};

Resolve the format "new interface name () {...}":
1. new represents the action of creating an object
 2. The interface name is the interface that the anonymous inner class needs to implement
 3. {...} This is the content of the anonymous inner class

In addition, pay attention to several issues:
1. Anonymous internal classes can only be used once when creating objects.
If you want to create an object multiple times and the content of the class is the same, you need to use a separately defined implementation class.
2. Anonymous objects can only be called once when [calling method].
If you want the same object to call multiple methods, you must give the object a name.
3. The anonymous inner class omits the implementation class / subclass name, but the anonymous object omits the object name
 Emphasize: anonymous inner class and anonymous object are not the same thing!!!

Code article

Interface

public interface MyInterface {
    public void Method1();
    void Method2();

}

Interface implementation class

public class MyInterImpl implements MyInterface{
    @Override
    public void Method1() {
        System.out.println("Override 1");
    }

    @Override
    public void Method2() {
        System.out.println("Override 2");
    }
}

Test class

public class DemoMain {
    public static void main(String[] args) {
        //Anonymous Inner Class 
        MyInterface obj = new MyInterface() {
            @Override
            public void Method1() {
                System.out.println("Overwrite Method1 method");
            }

            @Override
            public void Method2() {
                System.out.println("Overwrite Method2 method");

            }
        };
        obj.Method1();
        obj.Method2();
        System.out.println("===============");

        //Anonymous inner class anonymous object
        new MyInterface(){

            @Override
            public void Method1() {
                System.out.println("Override 1");
            }

            @Override
            public void Method2() {
                System.out.println("Override 2");

            }
        }.Method1();
        new MyInterface(){

            @Override
            public void Method1() {

                System.out.println("Override 1");
            }

            @Override
            public void Method2() {
                System.out.println("Override 2");

            }
        }.Method2();
    }
}

Class as a member variable type

Case: create a hero class. The member methods include name, age and weapon. Among them, weapon is a separate class.

Hero class

public class Hero {
    private String name;
    private int age;
    private Weapon weapon;

    public Hero() {
    }

    public Hero(String name, int age, Weapon weapon) {
        this.name = name;
        this.age = age;
        this.weapon = weapon;
    }
    public void Show(){
        System.out.println("I am:"+getName()+",this year"+getName()+"Years old."+"I use:"+weapon.getCode());
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Weapon getWeapon() {
        return weapon;
    }

    public void setWeapon(Weapon weapon) {
        this.weapon = weapon;
    }
}

Weapons

public class Weapon {//Weapons
    private String code;

    public Weapon() {
    }

    public Weapon(String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }
}

Test class

public class DemoMain {
    public static void main(String[] args) {
        //Create a hero object
        Hero hero = new Hero();
        hero.setName("Sun WuKong");
        hero.setAge(550);
        //Create a weapon object
        Weapon weapon = new Weapon();
        weapon.setCode("Golden cudgel");
        hero.setWeapon(weapon);
        hero.Show();
    }
}

Interface as a member variable type

Case: create a hero class. The member methods are: name and skill. Among them, the skill is implemented by the interface.

Hero class

public class Hero {
    private String name;//full name
    private Skill skill;//skill

    public Hero() {
    }

    public Hero(String name, Skill skill) {
        this.name = name;
        this.skill = skill;
    }
    public void showGame(){
        System.out.println("full name"+getName()+"Trigger skills:");
//        skill.method();
        skill.method();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Skill getSkill() {
        return skill;
    }

    public void setSkill(Skill skill) {
        this.skill = skill;
    }
}

Interface

public interface Skill {
    public void method();
}

Interface implementation class

public class SkillImpl implements Skill{
    @Override
    public void method() {
        System.out.println("Implement interface abstract method override overloading");
        System.out.println("Trigger skill: Pa Pa Pa");
    }
}

Test class

public class DemoGame {
    public static void main(String[] args) {
//        //Create an implementation class object
//        SkillImpl skillImpl = new SkillImpl();
//        //Create object
//        Hero hero = new Hero();
//        hero.setSkill(skillImpl);
//        hero.setName("Nezha");
//        hero.showGame();


        //Method 2
//        //Create an interface anonymous inner class and write skill methods
//        Skill skill = new Skill() {
//            @Override
//            public void method() {
//                System.out.println("trigger skill: Dangdang");
//            }
//        };
//                //Create object
//        Hero hero = new Hero();
//        hero.setName("Nezha");
//        hero.setSkill(skill);
//        hero.showGame();

        //Method 3: anonymous inner class anonymous object
        Hero hero = new Hero();
        hero.setName("nezha");
        hero.setSkill(new Skill() {
            @Override
            public void method() {
                System.out.println("Trigger skill: Dong Dong Dong");
            }
        });
        hero.showGame();
        };
    }

Interface as a parameter or return value of a method

import java.util.ArrayList;
import java.util.List;

/*
java.util.List This is the interface implemented by ArrayList.
 */
public interface DemoInterface {
    public static void main(String[] args) {
        //The interface name is on the left and the implementation class name is on the right. This is the way to write polymorphism
        List<String> list = new ArrayList<>();
        List<String> li = adds(list);
        for (int i = 0; i < li.size(); i++) {
            System.out.println(li.get(i));
        }

    }

    public static List<String> adds(List<String> list){
        list.add("Zhang San");
        list.add("Li Si");
        list.add("WangTwo ");
        list.add("Pockmarks");
        return  list;
    }
}

This chapter is over. Your favorite friends can communicate together in the comment area. Thank you for your support!

Topics: Java Eclipse intellij-idea