Question:
Basic Java question on abstract class?
Funk Master
2009-07-12 17:37:41 UTC
Can you help me?

#1
Why is it better to make an abstract class an interface if it has no implemented constructors or methods?

#2
Why are all methods in an interface abstract?
Three answers:
Blackcompe
2009-07-12 19:48:00 UTC
#1

I just spent so much time explaining how the two are exactly the same. Actually, it's better to use an interface when you run into the situation the person above me mentioned. Two interfaces allow the same method signature because the methods are abstract, and they won't run because there's no implementation (that's your answer to #2). Try that with abstract classes and you get problems.



abstract class Mother { void m(){} }

abstract class Father { void m(){} }



class Child extends Mother, Father {

void c(){super.m();}

}



Which method from its parents is called? So, this is not allowed in Java. You'd get a compile time error. If you would have you used interfaces, you'd be alright:



interface Mother { void m(); }

interface Father {void m(); }

class Child implements Mother, Father {

public void m(){}

}
spitfiredd
2009-07-12 18:15:31 UTC
1. There's probably a lot more answers to this one but the one glaring obvious one is that...in Object Oriented programming a sub class can only have one parent class, but can implement as many interfaces that you want it to. So by making an abstract class and interface you can work around the Double diamond of death that's prevalent in C++ (I am assuming that your talking about Java).



#2. Think about it for a second...do interfaces create new objects?!?! No, therefore you have to tag them as abstract so that when you implement the interface you have to override the methods.
2016-05-24 16:47:13 UTC
Provide the declaration for the method in the super class then let the subclasses inherit from the super class and provide their own implementation for that method


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...