Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 best method; if so how?

class Shape1 {
    int i = 1;
    void draw() {
        System.out.println("this is shape:" + i);
    }
}

class Shape2 {
    int i = 4;
    void draw() {
        System.out.println("this is shape2:" + i);
    }
}


class Shape {
    public static void main(String args[]) {
        Shape1 s1 = new Shape1();
        s1.draw();

        Shape2 s2 = new Shape2();
        s2.draw();
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
125 views
Welcome To Ask or Share your Answers For Others

1 Answer

You'd use an abstract class or interface here in order to make a common base class/interface that provides the void draw() method, e.g.

abstract class Shape() {
  void draw();
}

class Circle extends Shape {
   void draw() { ... }
}

...

Shape s = new Circle();
s.draw();

I'd generally use an interface. However you might use an abstract class if:

  1. You need/want to provide common functionality or class members (e.g. the int i member in your case).
  2. Your abstract methods have anything other than public access (which is the only access type allowed for interfaces), e.g. in my example, void draw() would have package visibility.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...