Home  >  Article  >  Java  >  Detailed explanation of the use of static keyword and inner classes in Java

Detailed explanation of the use of static keyword and inner classes in Java

WBOY
WBOYforward
2022-08-17 17:58:171435browse

This article brings you relevant knowledge about java, and introduces the use of static keywords and internal classes in Java in detail. The sample code in the article is explained in detail. Let’s take a look at it together. I hope everyone has to help.

Detailed explanation of the use of static keyword and inner classes in Java

Recommended study: "java Video Tutorial"

1. static keyword

In Java, Members modified by static are called static members or class members. They do not belong to a specific object and are shared by all objects.

1. Static modified member variables

static modified member variables are called static member variables

[Static member variable characteristics]:

  • Does not belong to a specific object. It is an attribute of the class. It is shared by all objects and is not stored in the space of an object.
  • Can be accessed through object reference (not recommended) ), can also be accessed through the class name, but it is generally recommended to use the class name to access
  • Class variables are stored in the method area
  • The life cycle accompanies the life of the class (that is, it changes with the loading of the class Created and destroyed when the class is unloaded)
public class Student{
    public String name;
    public String gender;
    public int age;
    public double score;
    public static String classRoom = "rj2104";

    public Student(String name, String gender, int age, double score) {
        this.name = name;
        this.gender = gender;
        this.age = age;
        this.score = score;
    }

    // ...
    public static void main(String[] args) {
        // 静态成员变量可以直接通过类名访问
        System.out.println(Student.classRoom);
        
        Student s1 = new Student("Li leilei", "男", 18, 3.8);
        Student s2 = new Student("Han MeiMei", "女", 19, 4.0);
        Student s3 = new Student("Jim", "男", 18, 2.6);
        
        // 也可以通过对象访问:但是classRoom是三个对象共享的
        System.out.println(s1.classRoom);
        System.out.println(s2.classRoom);
        System.out.println(s3.classRoom);

    }
}

2. static modified member method

Generally, data members in classes are set to private, and members The method is set to public.

In Java, member methods modified by static are called static member methods. They are methods of the class and are not unique to an object.

Static members are generally accessed through static methods.

public class Student2{
    // ...
    private static String classRoom = "rj2104";
    // ...
    public static String getClassRoom(){
        return classRoom;
    }
}

class TestStudent {
    public static void main(String[] args) {
        System.out.println(Student2.getClassRoom());
    }
}

[Static method characteristics]:

  • does not belong to a specific object, it is a class method
  • It can be called through the object or through the class name. When calling the static method name (...), it is more recommended to use the latter
  • You cannot access any non-static member variables and non-static member methods in static methods; because non-static methods have this parameter by default, but in static methods This reference cannot be passed when calling in the method; unless a new object is created in the static method, and then the object is accessed through the object reference
  • Static methods cannot be overridden and cannot be used to implement polymorphism

3. Initialization of static member variables

Static member variables are generally not initialized in the constructor. What is initialized in the constructor is the instance attributes related to the object

There are two types of initialization of static member variables: in-place initialization and static code block initialization.

In-place initialization: give the initial value directly when defining

public class Student2{
    // ...
    //就地初始化
    private static String classRoom = "rj2104";
    //...
}

Use static code block to complete initialization

public class Student2{
    // ...
    private static String classRoom;
    
    //静态代码块初始化
    static {
        classRoom = "rj2104";
    }

    // ...
}

2. Internal class

In Java In , a class can be defined inside another class or a method. The former is called an inner class and the latter is called an outer class. Inner classes are also a manifestation of encapsulation.

Internal classes and external classes share the same java source file, but after compilation, the internal class will form a separate bytecode file. Generally, the bytecode file name is: external class name $ internal Class name.class

public class OutClass {
    class InnerClass{
    }
}
// OutClass是外部类
// InnerClass是内部类

According to the location of the internal class definition, it can generally be divided into the following forms:

1. Member internal class (ordinary Inner class)

Instance inner class: member inner class that has not been statically modified

Static inner class: member inner class that has been statically modified

2. Local inner class

3. Anonymous inner class

1. Instance inner class

is a member inner class that has not been statically modified.

[Notes]:

  • Any member in the external class can be directly accessed in the instance internal class method
  • There cannot be static objects in the instance internal class Member variables; if they must be defined, they can only be static constants modified by static final. The constants are determined when the program is compiled.
  • The location of the inner class of the instance is the same as the location of the outer class member, so Also subject to public, private and other access qualifiers
  • Instance internal class objects must first have external class objects before they can be created
  • The non-static method of the instance internal class contains a default method A reference to an external class object and a reference to an internal class object of its own instance
  • When accessing a member with the same name in an instance's internal class method, access your own first. If you want to access a member of the external class with the same name, you must: External class name.this.Members with the same name are used to access
  • In the external class, members in the internal class of the instance cannot be directly accessed. If you want to access, you must first create an object of the internal class.
public class OutClass {
    private int a;
    static int b;
    int c;

    public void methodA() {
        a = 10;
        System.out.println(a);
    }

    public static void methodB() {
        System.out.println(b);
    }

    // 实例内部类:未被static修饰
    class InnerClass {
        int c;
//实例内部类当中 不能有静态的成员变量. 非要定义,那么只能是被static final修饰的
        public static final int d = 6;

        public void methodInner() {
// 在实例内部类中可以直接访问外部类中:任意访问限定符修饰的成员
            a = 100;
            b = 200;
            methodA();
            methodB();
            System.out.println(d);
// 如果外部类和实例内部类中具有相同名称成员时,优先访问的是内部类自己的
            c = 300;
            System.out.println(c);
// 如果要访问外部类同名成员时候,必须:外部类名称.this.同名成员名字
            OutClass.this.c = 400;
            System.out.println(OutClass.this.c);
        }
    }

    public static void main(String[] args) {
// 外部类:对象创建 以及 成员访问
        OutClass outClass = new OutClass();

        System.out.println(outClass.a);
        System.out.println(outClass.b);
        System.out.println(outClass.c);
        outClass.methodA();
        outClass.methodB();
        System.out.println("=============实例内部类的访问=============");
// 要访问实例内部类中成员,必须要创建实例内部类的对象
// 而普通内部类定义与外部类成员定义位置相同,因此创建实例内部类对象时必须借助外部类
// 创建实例内部类对象
        OutClass.InnerClass innerClass1 = new OutClass().new InnerClass();
        innerClass1.methodInner();
// 上述语法比较怪异,也可以先将外部类对象先创建出来,然后再创建实例内部类对象
        OutClass.InnerClass innerClass2 = outClass.new InnerClass();
        innerClass2.methodInner();
    }
}

2. Static inner class

The internal member class modified by static is called a static inner class. ,

[Note]:

In a static inner class, you can only access static members in the outer class, unless you create a new object of the outer class in the inner class, through the outer class object. Reference to access non-static members.

When creating a static inner class object, you do not need to create an outer class object first

public class OuterClass2 {
    public int data1 = 1;
    int data2 = 2;
    public static int data3 = 3;

    public void test() {
        System.out.println("out::test()");
    }

    // 静态内部类:被static修饰的成员内部类
    static class InnerClass2 {
        public int data4 = 4;
        int data5 = 5;
        public static int data6 = 6;

        public void func() {
            System.out.println("out::func()");

            //test();
            // 编译失败,在静态内部类中不能直接访问外部类中的非静态成员
            //System.out.println(data1);
            //System.out.println(data2);

            //外部类的非静态成员,需要通过外部类的对象的引用才能访问。
            OuterClass2 outerClass = new OuterClass2();
            System.out.println(outerClass.data1);
            System.out.println(outerClass.data2);
            outerClass.test();

            // 在静态内部类中只能访问外部类的静态成员
            System.out.println(data3);
            System.out.println(data4);
            System.out.println(data5);
            System.out.println(data5);
            System.out.println(data6);

        }
    }
    public static void main(String[] args) {
        // 静态内部类对象创建 和 成员访问
        OuterClass2.InnerClass2 innerClass2 = new OuterClass2.InnerClass2();
        innerClass2.func();

    }
}

3. Local inner class

is defined in the method body of the outer class or { }, Generally used very rarely.

【Precautions】

局部内部类只能在所定义的方法体内部使用

不能被public、static等修饰符修饰

局部内部类生成的字节码文件稍有区别:外部类名字$数字内部类名字.class

ppublic class OutClass {
    int a = 10;
    
    public void method(){
        int b = 10;
        // 局部内部类:定义在方法体内部
        // 不能被public、static等访问限定符修饰
        class InnerClass{
            public void methodInnerClass(){
                System.out.println(a);
                System.out.println(b);
            }
        }
        // 只能在该方法体内部使用,其他位置都不能用
        InnerClass innerClass = new InnerClass();
        innerClass.methodInnerClass();
    }
    
    public static void main(String[] args) {
    // OutClass.InnerClass innerClass = null; 编译失败
    }
}

4. 匿名内部类

匿名内部类,就是没有名字的一种嵌套类

匿名内部类形成的字节码文件文件名为:外部类名字$数字.class

4.1 使用匿名内部的好处与演示

在实际开发中,我们会遇到下面的情况:

一个接口/类的方法的某个执行过程在程序中只会执行一次,但为了使用它,我们需要创建它的实现类/子类去实现/重写方法。

代码中为了这一次的使用去创建一个类,未免太过麻烦,此时就可以使用匿名内部类来解决这个问题

首先来看我们正常的实现逻辑,假设有一个接口,接口当中只有一个方法

public interface Interface {
    void show();
}

为了使用该接口的show方法,我们需要去创建一个实现类,重写show方法的具体实现

public class Test implements Interface{
    @Override
    public void show() {
        System.out.println("只执行一次show()");
    }
}

public class Main {
    public static void main(String[] args) {
        Test test = new Test();
        test.show();
    }
}

如果实现类Test在程序中只使用一次,那么为了这一次的使用去创建一个类太过繁琐,这种情况下就可以用匿名内部类来实现,无需创建新的类,减少代码冗余,

看下面代码:

class Main {
    public static void main(String[] args) {
        //写法一
        Interface in = new Interface() {
            @Override
            public void show() {
                System.out.println("匿名内部类中重写show()");
            }
        };
        //调用接口方法
        in.show();
        
        //写法二
        new Interface() {
            @Override
            public void show() {
                System.out.println("匿名内部类中重写show()");
            }
        }.show();//调用接口方法
    }
}

4.2 匿名内部类的定义格式和使用

定义格式1:

接口名称 引用名 = new 接口名称() {
    // 覆盖重写所有抽象方法
};

引用名.方法调用

定义格式2:

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

对格式“new 接口名称() {…}”的理解:

new代表创建一个新的对象对象

接口名称就是匿名内部类需要实现哪个接口

{…}中是匿名内部类的内容

【注意事项】:

  • 匿名内部类,在【创建对象】的时候,只能使用唯一 一次。
  • 匿名对象,在【调用方法】的时候,只能调用唯一 一次。
  • 匿名内部类是省略了【实现类/子类名称】,但是匿名对象是省略了【对象名称】
  • 匿名内部类可以用在具体类、抽象类、接口上,且对方法个数没有要求。
public class Class {
    public void show(String s){
        System.out.println("Class::show()");
    }
}

public abstract class AbstractClass {
    abstract void show(String s);
}

public interface Interface {
    void show(String s);
}

public class TestDome {
    public static void main(String[] args) {

        //重写普通类的方法
        new Class(){
            @Override
            public void show(String s) {
                System.out.println(s);
            }
        }.show("普通类");

        //重写抽象类的抽象方法
        new AbstractClass(){
            @Override
            void show(String s) {
                System.out.println(s);
            }
        }.show("抽象类");

        //实现接口的抽象方法
        new Interface(){
            @Override
            public void show(String s) {
                System.out.println(s);
            }
        }.show("接口");

    }
}

执行结果:

推荐学习:《java视频教程

The above is the detailed content of Detailed explanation of the use of static keyword and inner classes in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete