简体   繁体   中英

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 ?

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 

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

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