我有一个接口
public interface I{
Status getStatus();
}
然后我有一个实现该接口的抽象类。
public abstract class C implements I{
public Status getStatus() {
return status;
}
}
我想从另一个类访问getstatus()方法,我尝试过了
C status = new C();
但是我得到错误“不能实例化类型C”
任何帮助都将不胜感激!谢谢。
发布于 2013-09-05 21:54:56
不能为抽象类创建对象,编写扩展抽象类并使用该类对象调用方法的具体类。
class test extends c{
..........
}
c obj1= new test();
obj1.getStatus();
发布于 2013-09-05 21:56:14
根据文档
A class type should be declared abstract only if the intent is that subclasses
can be created to complete the implementation. If the intent is simply to prevent
instantiation of a class, the proper way to express this is to declare a
constructor of no arguments, make it private, never invoke it, and declare no
other constructors.
抽象类可以没有抽象的方法,但是它必须有一个有效的用例(比如从子类调用super )。不能实例化(创建抽象类的对象)。
,所以要么删除抽象关键字,要么创建扩展抽象类.的另一个类。
Ans只是为了记录一下,当一个抽象类实现一个接口时,您不需要在抽象类中实现接口方法(如果您的设计要求这样做的话,您可以这样做)。但是,如果没有在实现抽象类的抽象类中实现接口方法,则需要在抽象类的第一个具体子类中实现相同的方法。另外,如果您确实在抽象类中实现了接口方法,那么就不需要在抽象类的具体子类中再次实现它们。不过,你总可以重写它。
发布于 2013-09-05 21:50:55
https://stackoverflow.com/questions/18650776
复制