Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implementing abstract methods/classes in java

Can I implement abstract methods in an abstract base class A in java?

If the answer is yes and there is an implemented abstract method in a base class A and there is a derived class B from A (B is not abstract). Does B still has to implement that base abstract method?

like image 943
Greg Oks Avatar asked Dec 13 '22 08:12

Greg Oks


2 Answers

If I understand your question correctly, Yes.

public abstract class TopClass {
  public abstract void methodA();
  public abstract void methodB();
}

public abstract class ClassA extends TopClass {
  @Override
  public void methodA() {
    // Implementation
  }
}

public class ClassB extends ClassA {
  @Override
  public void methodB() {
    // Implementation
  }
}

In this example, ClassB will compile. It will use it's own implementation of methodB(), and ClassA's implementation of methodA(). You could also override methodA() in ClassB if desired.

like image 127
raistlin0788 Avatar answered Jan 04 '23 10:01

raistlin0788


You could have two abstract classes, X and Y, where Y extends X. In that case it could make sense for Y to implement an abstract method of X, while still being abstract. Another non-abstract class Z could extend Y. However, in your example, for A to implement its own abstract methods is a contradiction, the point of making them abstract is so it doesn't provide implementations, it just specifies what the method signatures should look like.

like image 32
Nathan Hughes Avatar answered Jan 04 '23 11:01

Nathan Hughes