Abhishek Goel
Abhishek Goel

Reputation: 19731

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.

Upvotes: 1

Views: 8778

Answers (5)

TheXDShrimp
TheXDShrimp

Reputation: 116

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

Upvotes: 0

Aniket Thakur
Aniket Thakur

Reputation: 68905

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.

Upvotes: 4

Suresh Atta
Suresh Atta

Reputation: 121998

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

Upvotes: 2

Siva
Siva

Reputation: 1940

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();

Upvotes: 4

SpringLearner
SpringLearner

Reputation: 13844

You can not instantiate abstract class

Upvotes: 2

Related Questions