[Java Base 10] Internal Classes and Polymorphisms

1. Internal Classes

In java, classes can be defined inside another class, which we call an inner class, while outer classes are outer classes. There is a complete structure within a class that serves only external classes. Internal classes provide easier access to members of external classes, internal classes provide better encapsulation, and can be better controlled with permission modifiers.

// format
public class Class name {
    // Internal Class
    Permission modifier [static] class Internal Class Name {
        ...
    }
}

1.1 Static Internal Class

Static internal classes are classes decorated with static and are part of external classes. His features are the same as ordinary classes, but in different locations.

// format
public class Outer {
    public static class Inner {
        ...
    }
}
public class StaticInnerClass1 {
    public static String str = "Version 1.0";
    public static int num = 10;
    private String name;

    public static class Inner {
        private String type;
        private int age;

        public Inner() {
        }

        public Inner(String type, int age) {
            this.type = type;
            this.age = age;
        }

        public void show() {
            System.out.println(str);
            System.out.println(num);
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public int getAge() {
            return age;
        }

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

    public String getName() {
        return name;
    }

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

    public static void main(String[] args) {
    // Internal Class Instantiation
        StaticInnerClass1.Inner inner = new StaticInnerClass1.Inner();
        inner.show();
    }
}

Be careful:

Static internal classes have direct access to static members of external classes
Static internal classes cannot directly access external instance members

1.2 Member Inner Class

The member internal class is similar to the static internal class except that the static keyword modifier is not added. At jdk1.6 Static members cannot be defined in member internal classes until later versions.

// format
 Modifier class Class name {
    ...
    Modifier class Internal Class Class Name {
        ...
    }
}
// Member internal class call
 External Class.Internal class object name = new External Class Constructor().new Internal Class Constructor()
// Example
public class MemberInnerClass {

    public static int flag = 0;

    private String name;
    private int age;

    public MemberInnerClass() {
    }

    public MemberInnerClass(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public class Inner {

        private String sex;
        private int num;

        public Inner() {
        }

        public Inner(String sex, int num) {
            this.sex = sex;
            this.num = num;
        }

        public void show() {
            System.out.println(flag);
            System.out.println(name);
            System.out.println(age);
            System.out.println(sex);
            System.out.println(num);
        }

        public String getSex() {
            return sex;
        }

        public void setSex(String sex) {
            this.sex = sex;
        }

        public int getNum() {
            return num;
        }

        public void setNum(int num) {
            this.num = num;
        }
    }

    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 static void main(String[] args) {
        MemberInnerClass.Inner inner = new MemberInnerClass("Zhang San", 18).new Inner("male", 1);
        inner.show();
    }
}

Characteristic:

  • Objects belonging to external classes, consistent with class characteristics
  • Static members cannot be created, static members need to use final
  • Direct access to external and static members

1.3 Local Internal Classes

This is a very strange grammar, which is rarely used in normal situations and only understood.

Local internal classes are placed in code blocks, constructors, and methods.

// Example
public class PartialInnerClass {
    {
        class Dog{
        }

        Dog dog = new Dog();
    }

    public PartialInnerClass() {
        class Cat{
        }
        Cat cat = new Cat();
    }

    public static void main(String[] args) {
        class Pig{
        }
        Pig pig = new Pig();
    }
}

1.4 Anonymous Internal Class

An anonymous internal class is essentially a local internal class without a name, defined primarily in methods and code blocks. The primary goal is to simplify the code.

// format
new (class|abstract class|Interface) {
    ...
}

Characteristic:
Anonymous inner class is an inner class without a name
An anonymous object is created when an anonymous internal class is written
A subclass of the current class created by an anonymous internal class

// Example
public interface AnonymousInnerClass {

    void show();

    static void main(String[] args) {
        AnonymousInnerClass anonymousInnerClass = new AnonymousInnerClass() {
            @Override
            public void show() {
                System.out.println("Anonymous Class Creation");
            }
        };
        anonymousInnerClass.show();
    }
}

As you can see above, AnonymousInnerClass appears to have created objects directly, but it is not. The object obtained by the anonymousInnerClass instance is actually an implementation class or subclass of the interface. This is a feature of anonymous internal classes, which are created as subclasses. Subclass objects can be assigned directly to the parent class, which is one of the three main features of polymorphism, the face of objects. Next we will introduce this part.

1.5 Inner Class Example

The following example shows how to call local, member, and external class member variables

public class Other {

    private int number = 10;

    public class Inner {
        private int number = 5;

        public void show() {
            int number = 2;
            // 2
            System.out.println(number);
            // 5
            System.out.println(this.number);
            // 10
            System.out.println(Other.this.number);
        }
    }

    public static void main(String[] args) {
        Inner inner = new Other().new Inner();
        inner.show();
    }
}

2. Polymorphism

Objects of the same type have different characteristics when performing the same behavior. For a simple example, both dogs and cats can be abstracted into classes, which can also be subclasses of animals. Then cats and dogs are subclasses of animals, both of which implement barking. When different subclasses perform different barking behaviors, the results will be different.

2.1 Format and Member Access Features

// format
 Class object = new Subclass()

Interface Object = new Implementation Class()

Access features:

  • Variable: Compile and invoke depend on the parent class
  • Method: Compile to see parent class, call to see subclass

2.2 Polymorphism

Excellent:

  • Decoupling, easy to expand and maintain
  • Formal parameters can define a parent class, pass arguments as subclasses, which shows extensibility.

Bad:

  • In polymorphic cases, the unique functionality of subclasses cannot be used

2.3 Type Conversion

Automatic type conversion: Subclasses or implementation class instance objects can be directly assigned to the parent or interface

Cast type conversion: Like base type casts, subclass object variables= (subclasses) parent type variables, this kind of conversion also solves the disadvantage of not being able to use subclass independent functions.

Mandatory type conversion issues:

- An exception is thrown if the child is not a real child of the parent ClassCastException
- Casting is commonly used instanceof Make a judgment
// format
 Class variable instanceof Class name
// Return result is of boolean type

2.4 Example

// Interface
public interface Animal {
    void bark();
}

public class Cat implements Animal{
    @Override
    public void bark() {
        System.out.println("The kitten mews.");
    }
}

public class Dog implements Animal {
    @Override
    public void bark() {
        System.out.println("The puppy barked.");
    }
}

public class Demo {
    public static void getBark(Animal animal) {
        animal.bark();
    }

    public static void main(String[] args) {
        // Mew
        getBark(new Cat());

        // Emit a dog bark
        getBark(new Dog());
    }
}

At the end of this chapter, for personal learning and getting started with little white, don't gush! Hope you all appreciate the collection support more!

Source code [GitHub] [code cloud]

Keywords: Java

Added by kaeRock on Thu, 23 Dec 2021 01:17:16 +0200