简体   繁体   English

如何在Java中使用同名类的实例

[英]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. 我想创建一个类B的实例,该实例不是A的内部类的一部分。

How can I achieve this? 我该如何实现? I'd like the class name to remain the same for both B classes. 我希望两个B类的类名保持相同。

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 . 您可以使用B的全限定名来始终引用它: 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). 如果该类在未命名(默认)包中(即,如果在其.java文件顶部没有package声明),则此方法将无效 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 例如packageName.ABpackageName.B

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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