简体   繁体   中英

How to create abstract class object which implements interface ( JAVA )

I have an interface

public interface I{
  Status getStatus();
}

then I have an abstract class implementing that interface

public abstract class C implements I{
       public Status getStatus() {
        return status;
    }
}

I want to access the getstatus() method from another class, I have tried

C status = new C();

but I am getting error "Cannot instantiate the type C"

Any help will be highly appreciated..!! thanx.

You can not create object for an abstract class Write a concrete class which extends your abstract class and use that class object to call the method

 class test extends c{
      ..........
     }

    c  obj1= new test();
   obj1.getStatus();

According to docs

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.

Abstract class can have not abstract methods but it must have a valid use case(like calling super from subclass). You cannot instantiate(create objects of abstract class).

So either remove abstract keyword or create another class that extends your abstract class.

Ans just for the record when an abstract class implements an interface you need not implement the interface methods in abstract class(though you can if your design dictates so). But in case you don't implement interface methods in the abstract class implementing it you need to implement the same in first concrete subclass of your abstract class. Also if you do implement you interface methods in abstract class then no need to implement them again in the concrete subclass of the abstract class. You can always override it though.

Assuming that your class must be abstract .

You cannot instantiate an abstract class .

What you can do is,Let any child to extends that class and create object for that.

Abstract Methods and Classes

你不能实例化抽象类

If you really abstract methods in class C, then I recommend simply using a regular class. You can still extends that calls as well.

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