简体   繁体   English

从同一包中的其他类调用其他Java类名称

[英]Call other java class name from other class in same package

I have 5 classes namely c1, c2, c3, container ,main in same package. 我有5个类,即c1,c2,c3,container,主要位于同一包中。

From main class I am going to print class names of c1, c2. 从主类中,我将打印c1,c2的类名称。 c3 is super class for c1 and c2. c3是c1和c2的超类。

I want to print as 我想打印为

my name is c1 我叫c1

my name is c2 我叫c2

super class is c3 超类是c3

but it prints only 但只打印

my name is c3 我叫c3

my name is c3 我叫c3

super class is main 超级班是主要的

Here is my main class 这是我的主班

    class main{
        public static void main(String[] argh) {
            Container cont= new Container();
            c3 o1 = cont.getc3("c1");
            c3 o2 = cont.getc3("c2");
            System.out.println("My name is: " + o1.getClass().getName());
            System.out.println("My name is: " + o2.getClass().getName());
            System.out.println("Our superclass is: " + o1.getClass().getSuperclass().getName());

        }
    }

Here is my container class 这是我的集装箱班

    class container extends main {

        private String name;

        public c3 getc3(String string) {
            // TODO Auto-generated method stub
            return new c3(string);
        }

        public String getName() {
            System.out.println("-------------------------"+name);
            return name;
        }

        public String toString() {
            return getName();
        }

    }

Here is c3 class which is super class 这是c3类,是超类

class c3 extends main {

    private String name;
    private String string1;


    public c3(String string1) {
        string1 = string1;
    }


    public String getName() {
        return name;
    }

    public String toString() {
        return getName();
    }

    public String getString1() {
        return string1;
    }

    public void setString1(String string1) {
        this.string1 = string1;
    }

}

Here is c1 class 这是C1班

class c1 extends c3{

    public c1(String string1) {
        super(string1);
        // TODO Auto-generated constructor stub
    }

}

here is c2 这是c2

class c1 extends c3{

    public c2(String string1) {
        super(string1);
        // TODO Auto-generated constructor stub
    }

}

Your getc3 method returns objects of c3 class. 您的getc3方法返回c3类的对象。 The fact that you pass to it the Strings "c1" and "c2" doesn't make a difference. 您将字符串“ c1”和“ c2”传递给它的事实没有任何区别。

You'll have to change the implementation of public c3 getc3(String string) if you wish it to return isntances of c1 or c2 . 如果希望返回c1c2等号,则必须更改public c3 getc3(String string)的实现。 For example : 例如 :

    public c3 getc3(String string) {
        if (string.equals("c1"))
            return new c1(string);
        else if (string.equals("c2"))
            return new c2(string);
        else
            return new c3(string);
    }

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

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