How and when to use an abstract class

前端 未结 6 1607
梦毁少年i
梦毁少年i 2020-12-04 12:42

This is my test program in Java. I want to know how much abstract class is more important here and why we use abstract class for this.

Is it a mandatory or is it bes

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-04 13:34

    Abstract class, as its name suggest is abstract.

    Abstract class doesn't talk about the implementation part. In fact, we extend the abstract class to provide the implementation for its abstract methods. It can also have non-abstract methods.

    Check here : Use of Abstract Class in Java

    EDIT :

    Sample Code :

    abstract class Shapes {
    
     int i=1;
     abstract void draw(); 
    
     // Remember : Non-abstract methods are also allowed 
     void fill() {
         System.out.println("Non abstract method - fill");
     }
    }
    
    class Shape1 extends Shapes {
    
     int i=1;
     void draw(){
     System.out.println("This is Shape 1:"+i);
     }
    }
    
    class Shape2 extends Shapes {
        int i=2;
        void draw() {
            System.out.println("This is Shape 2:"+i);
        }
    }
    
    class Shape {
    
    public static void main(String args[])
           {
            Shape1 s1 = new Shape1();
            s1.draw();                     // Prints This is Shape 1:1
    
            Shape2 s2 = new Shape2();
            s2.draw();                     // Prints This is Shape 2:2
           }
      }
    

提交回复
热议问题