简体   繁体   English

如何将Java类放入对象并使用它的方法

[英]How to put a java class in a Object and use it methods

It is easy to put a class into a Object. 将类放入对象很容易。 But when I try to perform methods on it at Line 36: aClass.getInfo(3); 但是,当我尝试在第36行对其执行方法时: aClass.getInfo(3); I get a cannot find symbol and cannot compile. 我得到了cannot find symbol并且无法编译。 How could I use a class in a Object? 如何在对象中使用类? The aim is to use either classA or classB, depending on an int or something else. 目的是根据int或其他类型使用classA或classB。

package testit;

public class TestIt {

    Object aClass;

    public interface InFace {

        void getInfo(int i);
    }

    public class ClassA implements InFace {

        @Override
        public void getInfo(int i) {
        System.out.println("ClassA: " + this.getClass() + " " + i);
        }
    }

    public class ClassB implements InFace {

        @Override
        public void getInfo(int i) {
        System.out.println("ClassB: " + this.getClass() + " " + i);
        }
    }

    public void testClass() {
        ClassA testA = new ClassA();
        ClassB testB = new ClassB();
        testA.getInfo(1);
        testB.getInfo(2);
        int i = 1;
        if (i == 1) {
            aClass = testA;
        } else {
            aClass = testB;
        }

        System.out.println("aClass: " + aClass.getClass());

//        aClass.getInfo(3);
    }

    public static void main(String[] args) {
        TestIt test = new TestIt();
        test.testClass();
    }
}

Since aClass will hold only ClassA or ClassB , which are both subtypes of InFace , you can change 由于aClass仅包含ClassAClassB ,它们都是InFace子类型, InFace可以更改

Object aClass;

to

InFace aClass;

Then, your variable of type InFace will support a method, called getInfo(int i) and your code will compile. 然后,您的InFace类型的变量将支持一个名为getInfo(int i)的方法,并且您的代码将进行编译。

You should use InFace to declare your Object aClass; 您应该使用InFace来声明您的Object aClass; , because both of your classes implements that interface: ,因为您的两个类都实现了该接口:

InFace aClass;

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

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