Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what must be implemented from an abstract class in java?

I have two questions really. I'm trying to get a handle on how inheritance works.

If I have an abstract class to inherit from, and it has a method that is not labelled abstract does this method still need to be implemented in the subclass?

If I have a subclass that is inheriting from another subclass, which is then inheriting from an abstract class, does the lowest subclass need to implement the methods in the abstract class? Or because the methods have been implemented in the middle subclass, they don't need to be implemented again?

Thank you!

like image 276
Joshua Oliphant Avatar asked Jun 07 '13 01:06

Joshua Oliphant


2 Answers

An abstract class is a class that is declared abstract. It may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.

An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:

abstract void moveTo(double deltaX, double deltaY);

If a class includes abstract methods, the class itself must be declared abstract, as in:

public abstract class GraphicObject {
    // declare fields
    // declare non-abstract methods
    abstract void draw();
}

When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract

like image 172
Wils Avatar answered Oct 20 '22 02:10

Wils


  1. If the method is not abstract it has been implemented already, when you subclass the abstract class you inherit the method implementation, re-implementing it would be overriding it. If the method was declared abstract you must implement or get compile-time error if the subclass is also not declared abstract.
  2. If you are inheriting from a class A extends AbstractClass that is not abstract then A must have implemented any abstract methods or again compileerror. If it hasn't implemented any abstract classes then A must also be abstract and responsibility of implementing the abstract methods fall on subclassers of A. Any sublcassers that do not implement the method must also be declared abstract untill finally a subclass implements it.
like image 41
arynaq Avatar answered Oct 20 '22 00:10

arynaq