Object-Oriented Programming: In-depth understanding of the use of inner classes and abstract classes


insert image description here

Inner classes and abstract classes are important features of object-oriented programming in Java, and they are used for different scenarios and purposes respectively.

1. Use of inner classes:

An inner class is a class defined inside another class, it can directly access the members of the outer class, and can play a certain role of encapsulation. Inner classes are of the following types:

1.1 Member inner class:

Defined in the member position of the class, you can access all members of the external class, including private members. When creating an instance of a member's inner class, you need to create an instance of the outer class first, and then use the instance of the outer class to create an instance of the inner class.

A member inner class is a class that is defined inside a class and is defined directly at the member position of the class. It is similar to ordinary member variables and member methods, and can access members of external classes, including private members. Members of inner classes can also use references to outer classes OuterClass.thisto access instances of outer classes.

The following is a code example of a member inner class:

public class OuterClass {
    
    
    private int outerValue = 10;

    // 成员内部类
    public class InnerClass {
    
    
        private int innerValue = 20;

        public void display() {
    
    
            System.out.println("Outer value: " + outerValue);
            System.out.println("Inner value: " + innerValue);
        }
    }

    public static void main(String[] args) {
    
    
        OuterClass outerObj = new OuterClass();
        OuterClass.InnerClass innerObj = outerObj.new InnerClass();

        innerObj.display();
    }
}

In the above example, OuterClassis the outer class and InnerClassis a member of the inner class. In mainthe method, an instance of the outer class is first created outerObj, and then outerObjan instance of the inner class is created through to innerObj, which is how the member inner class is used.

1.1.1 The main characteristics of member inner classes are:

  • Members of the outer class, including private members, can be accessed directly.
  • Members of the inner class must be stored in the instance object of the outer class, so an instance of the inner class cannot be created without an instance of the outer class.

Member inner classes are typically used in the following situations:

  • Is closely related to the outer class and needs to directly access the members of the outer class.
  • It is necessary to create multiple independent inner class objects, each inner class object has its own state, but shares the data of the outer class.

It should be noted that if the member inner class does not need to access the members of the outer class, it can be defined as a static inner class, which can save some memory overhead. Static inner classes have no direct association with outer classes and can create objects independently.

1.2 Local inner classes:

Defined inside a method or code block, the scope of action is limited to the method or code block where it is located. The local inner class can access the parameters and local variables of the outer method, but these parameters and variables must be final or effectively final.
A local inner class is a class defined inside a method, which can only be used inside the method, and its scope is limited to the inside of the method. Local inner classes are invisible to outer classes and other methods.

The following is a code example of a local inner class:

public class OuterClass {
    
    
    private int outerValue = 10;

    public void outerMethod() {
    
    
        int localVar = 5;

        // 局部内部类
        class LocalInnerClass {
    
    
            public void display() {
    
    
                // 局部内部类可以访问外部类的实例变量和方法
                System.out.println("Outer value: " + outerValue);
                System.out.println("Local variable: " + localVar);
            }
        }

        // 创建局部内部类的实例,并调用其方法
        LocalInnerClass innerObj = new LocalInnerClass();
        innerObj.display();
    }

    public static void main(String[] args) {
    
    
        OuterClass outerObj = new OuterClass();
        outerObj.outerMethod();
    }
}

In the above example, OuterClassit is the outer class, and outerMethoda local inner class is defined inside the method LocalInnerClass. Local inner classes LocalInnerClasscan only outerMethodbe used inside methods.

1.2.1 The main features of local inner classes are:

  • Defined inside a method, it can only be used inside that method, and its scope is limited to the inside of the method.
  • The local inner class can access the local variables of the outer method and the instance variables and methods of the outer class, but the local variables must be finalor effectively final(that is, not modifiable).
  • A local inner class is invisible to the outer class and other methods, and can only be used inside the method in which it is defined.

1.2.2 Local inner classes are usually used in the following situations:

  • When the functionality of a class is only used inside a specific method and you don't want the class to be visible to other methods, you can define it as a local inner class.
  • Local inner classes can encapsulate the code in a more fine-grained manner, improving the security and readability of the code.

In short, local inner classes are suitable for use only within a specific method, and their scope is limited to that method.

1.3 Static inner class:

An inner class decorated with staticis similar to an ordinary class, except that it is nested inside other classes. A static inner class cannot access non-static members of the outer class, only static members of the outer class.

When using inner classes, different inner class types should be selected according to actual needs. For example, if the inner class needs to access the members of the outer class, you can use the member inner class; if the inner class is only used in a certain method and does not need to access the non-final variables of the outer class, you can use the local inner class; if the inner class does not Depending on the instance of the outer class, a static inner class can be used.

A static inner class is a class defined inside a class and staticdecorated with keywords. Unlike the member inner class, the static inner class does not depend on the instance of the outer class, and can directly create an instance of the inner class without first creating an instance of the outer class.

The following is a code example of a static inner class:

public class OuterClass {
    
    
    private static int outerValue = 10;

    // 静态内部类
    public static class StaticInnerClass {
    
    
        private int innerValue = 20;

        public void display() {
    
    
            System.out.println("Outer value: " + outerValue);
            System.out.println("Inner value: " + innerValue);
        }
    }

    public static void main(String[] args) {
    
    
        // 创建静态内部类的实例,不需要先创建外部类的实例
        StaticInnerClass innerObj = new StaticInnerClass();
        innerObj.display();
    }
}

In the above example, OuterClassit is the outer class and StaticInnerClassthe static inner class. In mainthe method, an instance of the static inner class is directly created innerObjwithout first creating an instance of the outer class.

1.3.1 The main features of static inner classes are:

  • An instance of an inner class can be created directly without first creating an instance of the outer class.
  • A static inner class cannot access non-static members of the outer class, only static members of the outer class.

1.3.2 Static inner classes are usually used in the following situations:

  • When the inner class does not need to access the instance variables or methods of the outer class, it can be defined as a static inner class, which can save memory overhead.
  • A static inner class can be used as an independent class to avoid coupling with instances of the outer class.

In short, the static inner class is suitable for situations where there is no need to access the members of the outer class instance, and it has nothing to do with the outer class instance.

1.4 Anonymous inner class:

An anonymous inner class is a special inner class that does not explicitly define a class name, but creates an instance directly where it is used. Often, using anonymous inner classes simplifies code, especially if you need to create a class that is used only once.

Anonymous inner classes are typically used in the following situations:

1.4.1 Implement the interface:

Anonymous inner classes are used when you need to create an instance of a class that implements an interface. For example:

interface MyInterface {
    
    
    void doSomething();
}

public class MyClass {
    
    
    public void methodWithInterface() {
    
    
        MyInterface myInterface = new MyInterface() {
    
    
            @Override
            public void doSomething() {
    
    
                System.out.println("Doing something...");
            }
        };
        myInterface.doSomething();
    }
}

1.4.2 Inheritance class:

When you need to create an instance of a class that inherits from it, you can use an anonymous inner class. For example:

class MyBaseClass {
    
    
    void display() {
    
    
        System.out.println("Base class method.");
    }
}

public class MyClass {
    
    
    public void methodWithInheritance() {
    
    
        MyBaseClass myBaseClass = new MyBaseClass() {
    
    
            @Override
            void display() {
    
    
                System.out.println("Overridden method.");
            }
        };
        myBaseClass.display();
    }
}

Note that in anonymous inner classes, methods of parent classes or interfaces can be overridden, and additional methods and fields can be added. The scope of an anonymous inner class is limited to the block of code that created it, usually within a method.

While anonymous inner classes can simplify your code, there are some limitations and caveats:

  • An anonymous inner class cannot have a constructor because it has no class name and cannot call a constructor.
  • An anonymous inner class can only be used once and cannot be used again elsewhere.
  • Anonymous inner classes can access member variables and methods of outer classes, but these member variables and methods must be final or effectively final (versions after Java 8).

Generally speaking, anonymous inner class is a flexible and commonly used programming technique, suitable for some simple class implementation or temporary class requirements, which can simplify the code and enhance the readability of the code.

insert image description here

Second, the use of abstract classes:

An abstract class is a special class that cannot be instantiated and can only be used as a parent class for other classes. An abstract class can contain both abstract and non-abstract methods. An abstract method is a method that has no concrete implementation and must be overridden in a subclass. Non-abstract methods can have concrete implementations, and subclasses can directly inherit and use them.

The main purpose of using abstract classes is to achieve code reuse and scalability. The abstract class defines some common methods in it, and subclasses can inherit these methods and rewrite them according to their own special needs. Abstract classes can also force subclasses to implement certain functions by defining abstract methods, which can ensure that subclasses have the same interface, and the specific implementation is determined by subclasses themselves.

When using abstract classes, you need to pay attention to the following points:

  • An abstract class cannot be instantiated and can only be used as a parent class for other classes.

  • Subclasses must implement all abstract methods in an abstract class, unless the subclass is also an abstract class.

  • An abstract class can contain non-abstract methods, and subclasses can inherit and use these non-abstract methods.

  • A class can only inherit from one abstract class, but can implement multiple interfaces.

In general, inner classes and abstract classes are important object-oriented programming features in Java, and they all have their own application scenarios and advantages. Reasonable use of inner classes and abstract classes can improve the readability, maintainability and extensibility of the code.

insert image description here

Guess you like

Origin blog.csdn.net/qq_43546721/article/details/131960952