Is it necessary for an abstract class to have at least one abstract method?
The subject of this post and the body ask two different questions:
Should it have at least one abstract member?
Is it necessary to have at least one abstract member?
The answer to #2 is definitively no.
The answer to #1 is subjective and a matter of style. Personally I would say yes. If your intent is to prevent a class (with no abstract methods) from being instantiated, the best way to handle this is with a privateprotected constructor, not by marking it abstract.
No, it is not necessary. You see this often back in "template method" design pattern, like HttpServlet, wherein each method already has default behaviour definied and you're free to override just one (or more) of them instead of all of them.
The HttpServlet class is merely abstract to prevent direct initialization by inadvertendly using new HttpServlet() which would otherwise basically have returned an empty, unimplemented and useless servlet instance.
In JDK 1.0 it was indeed necessary to have at least one abstract method in an abstract class. This restriction was removed in JDK 1.1 (1997? (I'm old)) and such classes added to the Java library, such as java.awt.event.KeyAdapter.
In C++ you need at least one pure virtual function to make a subclass necessary, and at least one virtual function to add RTTI to the class. Typically it makes sense to use the destructor.
Note when overriding non-abstract methods, using #Override is a good idea. It not only tells the reader important information about what the code is attempting to do, but also spots common errors where typos or incorrect parameter types prevents the override.
No - you can declare a class abstract without having any abstract methods. It may not make any sense conceptually for an instance of that class to exist, or you may want to ensure that only subclasses of that class can be instantiated (for whatever reason)
If a class has an abstract modifier on its declaration it becomes abstract class.
Related
Since we have default methods now in an interface,isn't it more like an abstract class with both abstract and non abstract methods ? When it comes to practical use, can we use interface and abstract class interchangeably ? Are there any scenarios where the difference between the two is still relevant ?
Yes, there are scenarios where the difference between the two is still relevant.
Interfaces can't have fields (except static ones).
Interfaces can't have constructors.
Interfaces can't have final methods.
Interfaces can't have non-public methods.
The first point is what really stops you from using an interface like a class. All the others can be worked around (although it might be ugly).
You still can't extend 2 abstract classes, but can implement several interfaces.
Sort of. The key difference is that abstract classes are classes and thus have the advantage that they can encapsulate state and have concrete methods which operate on that state. Interfaces cannot have state, and thus default methods can only operate in terms of other interfaces methods.
I have upvoted the answer by immibis. But personally I think, there few things which makes us decide which one to use, Abstract class or interface.
Abstract class has some specific features which an interface does not have. Like, interface doesn't allow you to describe any method inside it, where abstract class allows. This feature makes differences.
Please go thorough this post for the details if you want to...
http://javacodingtutorial.blogspot.de/2013/10/interface-vs-abstract-class.html
This is my question
What is the use of a Abstract class even though we cant instantiate a abstract class?
is there a indirect way of creating instances of an Abstract class?
Basically, an abstract class is a class that is not fully implemented. If you know that you will have several subclasses of a class, but that you will never declare objects of the class itself, you should consider making the class abstract. Say, for instance, that you have an array of items, and you want them to all act fairly similarly except in certain circumstances. You could make an abstract superclass, and have all these items be members of subclasses of it. Then have the method whose behaviors differ among the different items be abstract in the superclass - but implement them in the subclass. This way, you can put them all in one array (etc) but they will all respond differently to certain method calls.
Did you understand what is an interface in java ? It is in fact, a programming agreement between the architect, developers. That will not contain any method definitions but their signatures. Since architects need to assure to other world creatures who use this code that this works in all of their scenarios. The same way, if some code is so much standard, and an architect cum developer wishes to use it for a de-facto method, he may include that too in an interface. But this distinction made another introduction to java and that is called as Abstract Class concept.
Abstract classes have importance in relation to runtime polymorphism.
i am still reading factory patterns on head first. We have an pizzaStore example and trying to localize our pizzaStore class to let franchies freedom to have their own regional style.
To do this, we changed to pizzaStore class to abstract class, and moved our factory object to "abstract createPizza(String type);" method. It is ok, i understood why.
If you look at the picture, i underlined the sentence. What it means ? " if we really want to enforce, we could make the method final ? "
The point is that subclasses are supposed to implement createPizza, but are required by contract to not override orderPizza, just call it. This policy can be enforced by making the method final.
When you design a class for inheritance, you must generally take care of all the details involved in how exactly the class is supposed to be extended.
If you make a method final classes inheriting the method cannot overwrite it. This ensures that the implementation in PizzaStore is used by all the subclasses.
Source: http://docs.oracle.com/javase/tutorial/java/IandI/final.html
Declaring a method as final, prevents the subclasses from overidding it.
If you make orderPizza method final, you cant override in your subclasses, but you can still access them. methods marked with final cant be overriden in your subclass.
Final methods cannot be overridden thus any inheriting class has the same method, they are enforced to have that same method.
This means that ChicagoStylePizzaStore is not allowed to override orderPizza().
The java final keyword: final orderPizza() enforced that the sub classes cannot overide that method.
Class Chicago then has to call orderPizza() from PizzaStorre() and not from an own method with same name.
Is there a reason to use a 100% abstract class and not an interface ?
Can you give me a good example when to use both so I can grasp the concept a little?
Update:
100% Abstract class -> abstract class with only abstract methods.
I'm curios if there are differences between php and java regarding this aspect.
Update2:
Even if I understand most of the reasons I'm more interested in the conceptual more than technical reasons.
If by "100% abstract class" you mean "abstract class with no concrete methods", then I can think of a reason: visibility.
You can define an abstract method to be protected, and hence not part of the public API of the class. However, that seems like an odd design.
Another thing that came to my mind is when you expect to add common functionality to the base class - i.e. if it is likely to have some utility methods shared by all implementors, but these methods are not implemented.
Another thing - instance variables. You can have inheritable instance variables in the abstract class.
The one case where an "100% abstract class" may be advantageous over an interface is in places where API stability is a key concern.
If you write an API where other people are expected to implement your interface you have to stick to the interface. You can't add any methods to the interface later on because that would break all clients (you would have to work around this by implement a second interface and let your code check againt the usage with instanceof checks and provide an fallback).
If you realize the same with an class you can add (non abstract) methods later on without breaking the client.
Next to visibility, another reason could be to be able to specify a certain Constructor you want all implementations to implement, or define a certain property. But in general, I agree with Alexander that a 100% abstract class isn't a good idea. I would prefer an interface in most cases unless there's a very good reason not to use an interface.
I personally think the difference as conceptual more than technical. For instance it would be bad idea to have an interface called "Human" and implement them on Male and Female. It would make more sense to make the Human as class.
You can implement multiple interfaces and you should see interfaces as add-ons.
I'm not quite sure how to answer this conceptually anymore, but in practice I use interfaces for the following reasons:
To indicate different classes have a shared interface: that you can manipulate them / use them in the same way
You can implement multiple interfaces, but only extend one class
Reasons for using abstract classes:
To share functionality between similar objects. For example Porshe911 could extend Car, overwrite a few methods and keep the rest.
To write frameworks that people can adapt. For example by leaving a few crucial methods unimplemented and writing the rest of the class to be internally consistent provided you implement those few methods. An example would be a menu class with a single abstract method getMenuItems()
Your example of the 100% abstract class seems senseless to me. As far as I can see that would just make it an interface, with the added restriction that you can have only one.
100% Abstract class isn't good idea. For common structure of child classes uses Interface. For similiar classes with same some methods and not same others more better to use Abstract Class.
I have got a question in my finished interview that I wouldn't get the right answer.
Assume that we have 3 class, Base, Derivate1 and Derivate 2,
Their relations are shown as follow
public class Base {...}
public class Derivate1 extends Base {...}
public class Derivate2 extends Derivate1 {...}
Then we found out that Derivate1 and Derivate2 are unnecessary for our program, but their method implementations are useful. So, how can we get rid of Derivate1 and Derivate2 but still keep their methods? In this case, we are expecting that user cannot create new instance of Derivate1 and Derivate2, but they still can use the method implementations in Derivate1 and Derivate2. Of course, we are allow to change the code in class Base.
What do you think about that and can you tell what they're actually asking?
Thanks a lot.
PS.
There are abit of hints from my interviewer when I have discuss the them.
The derivate classes are from the third party. They are badly design, so we don't want our client to use them, which means user should not allow to create instance from the derivate classes.
The derviate class contains overriding methods that are useful for the Base class, we can create method with different name in the Base to implement those useful behavious in derviated classes.
And thank you for all those interesting answers...
Simple refactoring:
Copy all code from Derivate1 and Derivate2 into Base.
Delete Derivate1 and Derivate2 classes
Ensure no missing references (if you are already holding pointers to Derivate objects as Base, you should be good)
Compile
?????
Profit!
Even if you have more subclasses such as Derivate3 and Derivate4 down the hierarchy, there should be no problem in having them extend Base.
(non-static) Methods from Derivate1 and Derivate2 are only usable if we create Derivate1 and Derivate2 instances. Creating a Base instance (like with new Base()) will not give access to (non-static) method declared in subclasses.
So to keep the methods, one could add (refactor) them to the Base class. If we just don't want public constructors for the sub classes but keep the object graph as it is, on could use a Factory pattern to have them created on demand. But even in this case one had to cast the object returned by the factory to either Derivate1 or Derivate2 to use the (non-static) methods.
I guess I know what they wanted to hear, the common recommendation 'favour composition over inheritance'. So instead of saying Derivate1 is-a Base you do a Derivate1 has-a Base:
public class Derivate1 {
private Base base;
// ... more
}
public class Derivate2 {
private Derivate1 derivate1;
// ... more
}
No more inheritance and both Derivates can still use methods of their former super classes.
From the hints they gave you, I think the answer was adapter pattern, which sometimes is used for legacy code.
You can have a look at it here:
http://en.wikipedia.org/wiki/Adapter_pattern
We could do two things:
we could pull up some methods of Derivate1 and Derivate2 to Base, when this makes sense (as noted above)
we could make both Derivate1 and Derivate2 abstract: this prevents instantiation, but not inheritance
I think they meant extracting derivate to interface
If it makes sense, you can directly include these methods in your base class. But it depends on the meanings of this class, of course. If it is possible, you could ty to use static methods in a utility class. By the way, your developers will have to change their use of the API in both cases.
The first obvious thing is that each of the classes in the hierarchy is concrete - in general, either a type should be abstract, or a leaf type. Secondly, there isn't quite enough information as to what these methods are - if they override something in Base or Derived1, you can't move them into Base; if they are utility methods which would apply to any Base then they might be moved into Base, if they are independent of Base then then they could be moved into a helper class or a strategy.
But I would question the idea that a class is not required but its behaviour is - it sort of implies that the questioner is looking at designing an ontology rather than an object oriented program - the only reason a class exists is to provide behaviour, and coherently encapsulating a useful behaviour is a sufficient and necessary condition for a class to exist.
Since you do not own the derivate classes you cannot delete them. The base class is all yours so you have control. The client is yours so you have control there. So the best way would be to have an all new class that is exposed to the client. This class essentially creates the derivate instances (note: your client isn't dealing with it anymore) and use their useful functions.