Defining an abstract class without any abstract me

2019-01-30 10:08发布

Can I define an abstract class without adding an abstract method?

11条回答
神经病院院长
2楼-- · 2019-01-30 10:23

Yes you can. Sometimes you may get asked this question that what is the purpose doing this? The answer is: sometimes we have to restrict the class from instantiating by its own. In that case, we want user to extend our Abstract class and instantiate child class

查看更多
戒情不戒烟
3楼-- · 2019-01-30 10:26

yes, we can declare an abstract class without any abstract method. the purpose of declaring a class as abstract is not to instantiate the class.

so two cases

1) abstract class with abstract methods.

these type of classes, we must inherit a class from this abstract class and must override the abstract methods in our class, ex: GenricServlet class

2) abstract class without abstract methods.

these type of classes, we must inherit a class from this abstract class, ex: HttpServlet class purpose of doing is although you if you don't implement your logic in child class you can get the parent logic

please check the HttpServlet source code

查看更多
\"骚年 ilove
4楼-- · 2019-01-30 10:29

Yes you can. The abstract class used in java signifies that you can't create an object of the class. And an abstract method the subclasses have to provide an implementation for that method.

So you can easily define an abstract class without any abstract method.

As for Example :

public abstract class AbstractClass{

    public String nonAbstractMethodOne(String param1,String param2){
        String param = param1 + param2;
        return param;
    }

    public static void nonAbstractMethodTwo(String param){
        System.out.println("Value of param is "+param);
    }
}

This is fine.

查看更多
狗以群分
5楼-- · 2019-01-30 10:31

Yes we can have an abstract class without Abstract Methods as both are independent concepts. Declaring a class abstract means that it can not be instantiated on its own and can only be sub classed. Declaring a method abstract means that Method will be defined in the subclass.

查看更多
Ridiculous、
6楼-- · 2019-01-30 10:37

Yes, you can define an abstract class without an abstract method. However, if there is no method inside you might better go with an interface

查看更多
登录 后发表回答