13

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?
Greg
  • 773
  • 9
  • 22
911TurboS
  • 527
  • 2
  • 7
  • 14

8 Answers8

18
  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.
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • @911TurboS You should mark the answer as answered if it's correct (the button underneath the arrow-down symbol). – Rohan Feb 08 '12 at 16:45
14

@Override

@Override was introduced in Java 5 (and extended a little bit in Java 6). It's only informative. It says "I'm suppose to override something that already exist in parent class or interface.

IDE's like Eclipse can warn you in case there's no such parent method (by example if you mispell the name). In that case your method will not be invoked (because of the mispelling).

But don't worry too much about it.

Abstract class vs interface

An abstract class allows you define a basic functionality leaving undefined parts. An interface doesn't allow you to implement anything. You can program everything except the part that really changes in each case. So when you need it, you inherit and implement the missing part.

Override two methods

Yes. In Java you can override all methods not explicity declared as final in parent class. It's ok. If you want to make it unmodifiable you can declare it final. By example, if you want to declare an ordering you could:

public abstract class Ordering<X>
{
abstract boolean isLower(X a, X b);
abstract boolean isEquals(X a, X b);
   final boolean isGreater(X a, X b) {
      return !isLower(a, b) && !isEquals(a, b);
   }
}

Of course it may have sense to override isGreater to implement it another more efficient way (imagine it's costly to compare). But there are scenarios when you want to provide basic already implemented functionality (and then's when abstract classes are better than interfaces) or when you want to force some implementation (then's when final keyword show useful).

jondavidjohn
  • 61,812
  • 21
  • 118
  • 158
helios
  • 13,574
  • 2
  • 45
  • 55
  • 2
    Thanks a lot! Anyway you'll get used to abstract/interfaces and more by looking at examples. Spring framework is a good example. And in fact, if you know about design patterns: abstract classes relate very close to template method while interfaces relates to (among a lot of other things) strategy pattern. Template is extending by inheritance while strategy is extending by composition. Again: Spring framework with all its templates and componentes is a very good example. You'll find out with time. – helios Feb 08 '12 at 16:56
4

Abstract Classes allow you to store base level implementations (inheritance), while also producing a contract that guarantees inherited classes will implement specific functionality (interface) on their own...

While there will never be a instance of an Abstract Class, you can store shared functionality between inheritors...

I've always thought of them as Interfaces that allow base level implementations of certain methods...

jondavidjohn
  • 61,812
  • 21
  • 118
  • 158
2

The main difference between abstract classes and interfaces, is that interfaces only define an interface and abstract classes can also have an implementation and fields/properties.

An abstract class can be seen as a IS-A relation (e.g. a horse is an animal). For interface it mostly is some feature a class can have (e.g. INavigable, ISortable).

Also abstract methods cannot be instantiated (neither to interfaces).

Overriding functions are to show that a function has a base class implementation.

Also multiple inheritance is not possible/adviced with classes, therefore max. use only one base class and inherit from interfaces for other features.

Michel Keijzers
  • 15,025
  • 28
  • 93
  • 119
1

What is the purpose of @Override keyword, because if i omit it, it still works the same.

Legibility.

If i don't implement the abstract method, i get compilation error. So what is the difference to implementing an interface?

Interfaces don't allow you to include code.

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 abstract in Class A?

Yes it is overriding the parent method. You usually define a method as abstract to leave the implementation for the child (which MUST implement it or be abstract). If it's not abstract, you have to implement it.

m0skit0
  • 25,268
  • 11
  • 79
  • 127
  • 1
    Interfaces do allow you to include 'code', they are a declaration of how a client can interact(interface) with objects implementing that interface. They can be used as reference type which intern promotes polymorphism by encapsultaing the client from any abstract or concrete implementation. Variables can be declared in interfaces however will by default (and definition) be static as there will never be an instance of the interface. You use abstract methods to enforce concrete implementations that are either unknown or may change between child implementations – T I Feb 08 '12 at 16:54
1

What is the purpose of @Override keyword

It's later Java addition, which is for weak self-control. It's annotation, i.e. library class, not keyword.

So what is the difference to implementing an interface?

Little. Iterface is a class where all methods are abstract. Also, only one class parent is allowed, while it can be multiple interfaces. Also you can put members into class, but not into interface.

Then what is the purpose of explicitly Defining a method abstract in Class A?

You should declare it abstract only if it has no body. It is required for JVM to know that all descendants will have it.

Suzan Cioc
  • 29,281
  • 63
  • 213
  • 385
0

This article has some good concepts (and examples) regarding the title of your question.

Abstract Classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract Classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.

Suppose that you want to define a class with certain methods, but for whatever design purpose of your program/project, you want to make sure that an specific method (Abstract Method) must be implemented when the Abstract Class is extended.

Basically, the purpose of Abstract Classes is to define a Class with methods that:

  • must be declared (abstract) on the subclass
  • are optionally used (non-abstract) on the subclass


Additional Comment

  • Few years ago, I developed an application for Android (Java, not Kotlin), and during the usage of many libraries, I experienced the behaviour of extending my classes with Abstract Classes and due to the behaviour of this type of class, Android Studio automatically added to my code, all Abstract Methods that were part of the Abstract Class which I was extending.
ivanleoncz
  • 9,070
  • 7
  • 57
  • 49
0

The real usage comes into picture when you have multiple classes implementing and method1 is being invoked from method2. In this case, after executing method2, method1 in corresponding class will be executed.

public abstract class A {

    protected abstract void method1(int val); 

    protected void method2() { 
        System.out.println("This is Class A's method");
        //Let us I calculated something here, may be sum of two ints 
        method1(//pass above calculated int);
    } 
}

public class B extends A {

    @Override
    protected void method1(int val) {
        System.out.println("This is B's implementaiton of A's method");
        //Here you may do this class specific manipulation on val.
    } 
}  

Like that in class C you can manipulate common calculated some.

kosa
  • 65,990
  • 13
  • 130
  • 167