简体   繁体   中英

How to make instance with same name class in java

I want to create an instance of class B that isn't a part of A 's inner class.

How can I achieve this? I'd like the class name to remain the same for both B classes.

public class Sample {
    public static void main(String[] args) {
        A a = new A();
        a.show();
    }
}

class A {
    class B {
        public void show() {
            System.out.println("hello");
        }
    }

    public void show() {
        B b = new B();
        b.show();
    }
}

class B {
    public void show() {
        System.out.println("hellohello");
    }
}

使用B类,即完全合格的名称com.mypackage.mysubpackage.B的外部Bcom.mypackage.mysubpackage.AB的内部B.

You can use the fully-qualified name of B to always refer to it: packageName.B .

This won't work if the class is in the unnamed (default) package (ie if there is no package declaration on top of its .java file). This is yet another reason not to use the unnamed package at all (ie all your classes should be in a named package).

使用要创建其实例的类的完整标识符(无import语句)。

yourPackage.B variable = new yourPackage.B();

Replace your main method with the code below:

public static void main(String[] args) {

    A a = new A();
    a.show();
    //For Outer Class
    B bOuter =new B();
    bOuter.show();

    //For Inner Class
    A.B bInner=new A().new B();
    bInner.show();
}

Use complete qualified name to keep away from conflict among same classes name. Eg packageName.AB and packageName.B

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM