What's the point in having an abstract class with no abstract methods?

后端 未结 9 1516
一整个雨季
一整个雨季 2021-01-02 21:11

Can have an abstract class implementing all of its methods-- with no abstract methods in it.

Eg.:

public abstract class someClass          


        
9条回答
  •  难免孤独
    2021-01-02 21:44

    We generally use Abstraction concept with inheritance

    Consider using abstract classes if any of these statements apply to your situation:

    • You want to share code among several closely related classes.

    To answer your question,

    Why declare a class with concrete methods Abstract?

    One possible reason is to support inheritance without actually creating objects


    Assume you have two classes one Abstract and other Concrete

    Abstract class : AbsClass

    abstract class AbsClass {
      int a = 5;
    
      //Constructor
      public AbsClass() {
        System.out.println(a);
      }
    
      void methodA() {
        System.out.println(a + 10);
    
      }
    
    }
    

    and Concrete class : ConcreteClass

    class ConcreteClass {
      int a = 10;
    
     //Made the constructor Private to prevent from creating objects of this class
      private ConcreteClass() {
        System.out.println(a);
    
      }
    
      void methodA() {
        System.out.println(a + 10);
      }
    

    }

    The above two classes should function similarly (?) Until you try to Subclass them

    class AbsImplementer extends AbsClass {
    //Works fine
    
    }
    
    class ConcImplementer extends ConcreteClass {
    //Compilation Error Implicit super constructor ConcreteClass() is not visible
    
    
    }
    

提交回复
热议问题