Java创建类的八种写法

  • 常见写法
package classes;

public class ClassDemo8 {
    public static void main(String[] args) {
        System.out.println("基本写法");
    }
}
  • 普通类
package classes;

/**
 * 普通类
 */
public class ClassDemo1 {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.say();
    }
}
class Dog{
    void say(){
        System.out.println("旺旺");
    }
}
  • 成员内部类
package classes;

/**
 * 成员内部类
 */
public class ClassDemo2 {
    class Dog{
        void say(){
            System.out.println("旺旺");
        }
    }
    public static void main(String[] args) {
        classes.Dog dog = new classes.Dog();
        dog.say();
    }
}

  • 创建外部类中成员内部类的对象
package classes;

/**
 * 创建外部类中成员内部类的对象
 */
public class ClassDemo3 {

    public static void main(String[] args) {
        Outer.Inner inner = new Outer().new Inner();
        inner.say();
    }
}
class Outer{
    class Inner{
        void say(){
            System.out.println("inner say");
        }
    }

}
  • 创建类的私有成员内部类的对象并使用
package classes;

/**
 * 创建类的私有成员内部类的对象并使用
 */
public class ClassDemo4 {

    public static void main(String[] args) {
        OuterPrivate outerPrivate = new OuterPrivate();
        outerPrivate.sayInner();
    }
}

class OuterPrivate{
    private class Inner{
        void say(){
            System.out.println("inner say");
        }
    }
    void sayInner(){
        Inner inner = new Inner();
        inner.say();
    }
}
  • 局部内部类
package classes;

/**
 * 局部内部类
 */
public class ClassDemo5 {

    public static void main(String[] args) {
        class Dog{
            void say(){
                System.out.println("旺旺");
            }
        }
        Dog dog = new Dog();
        dog.say();
    }
}

  • 匿名内部类
package classes;

/**
 * 匿名内部类
 */
public class ClassDemo6 {

    public static void main(String[] args) {
        DogInterface dog = new DogInterface(){
            @Override
            public void say() {
                System.out.println("旺旺");
            }
        };
        dog.say();
    }
}
interface DogInterface{
    void say();
}

  • 静态成员内部类
package classes;

/**
 * 静态成员内部类
 */
public class ClassDemo7 {

    public static void main(String[] args) {
        OuterStatic.Dog dog = new OuterStatic.Dog();
        dog.say();
    }
}
class OuterStatic{
    static class Dog{
        void say(){
            System.out.println("旺旺");
        }
    }
}
posted @ 2021-06-06 16:38  HumorChen99  阅读(31)  评论(0编辑  收藏  举报  来源