Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 views
in Technique[技术] by (71.8m points)

overriding - Understanding the purpose of Abstract Classes in Java

Suppose I have two Classes, A and B. The A class is defined as abstract, while B extends this abstract class, and finally i test the result and both classes are part of same package.

public abstract class A {

    protected abstract void method1(); 

    protected void method2() { 
        System.out.println("This is Class A's method"); 
    } 
}

public class B extends A {

    @Override
    protected void method1() {
        System.out.println("This is B's implementaiton of A's method");
    } 
}  

and now when i test them:

B b = new B();
b.method1();
b.method2();  

I get expected output:

This is B's implementaiton of A's method
This is Class A's method

QUESTIONS:

  • What is the purpose of @Override keyword, because if I omit it, it still works the same.
  • If I don't implement the abstract method, I get a compilation error. So what is the difference from implementing an interface?
  • Also, I can implement method2() in B as well. Then the output changes to what is use in B. Isn't this also overriding the parent class method? Then what is the purpose of explicitly defining a method as abstract in Class A?
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
  1. @Override is not a keyword, it is an optional annotation that helps the compiler check that you indeed are overriding a method. If you say @Override but there is no method to override, the compiler will tell you that you've probably made a typo. Rename method1 to method12 to see the effect.
  2. Interface cannot have any implementations, while abstract class may optionally provide implementations for some of its methods. In addition, interfaces cannot have data members.
  3. Defining a method as abstract means that the derived class must provide an implementation. Not declaring it abstract says that derived classes simply can provide their own implementation, but they do not need to.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...