Jagan Mohan
Jagan Mohan

Reputation: 23

How to call a non abstract method of an abstract class directly without deriving the abstract class?

I have an abstract class which contains a non abstract method as follows.

abstract class myClass {     
    public void myNonAbstractMethod()
    {
        //some logic goes here...
    }   
}

Now my question is, is it possible to call myNonAbstractMethod() directly without deriving myClass?

Upvotes: 2

Views: 7872

Answers (2)

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44448

You cannot instantiate an abstract class meaning you aren't able to call an instance method directly from it.

You can make the method static if you really don't want to derive it, but a subclass would be best.

public class Test {
    public static void main(String[] args) {
         System.out.println(SomeTest.size());
    }
}

abstract class SomeTest {
    public static int size() {
        return 5;
    }
}

Output:

5

Upvotes: 5

Tigran
Tigran

Reputation: 62286

No, as abstract class can not be instantiated by itself. You have to derive from it in order to be able to construct an instance.

 public abstract class Base {

   public void BaseMethod() {
   }
 }

 var bs = new Base();  //FAIL TO COPMILE

but..

 public class Derived : Base {

 }

 var bs = new Derived ();  //OK
 bs.BaseMethod(); //OK 

Upvotes: 5

Related Questions