Abstract Base Class or Class? - java

For my semester project, my team and I are supposed to make a .jar file (library, not runnable) that contains a game development framework and demonstrate the concepts of OOP. Its supposed to be a FRAMEWORK and another team is supposed to use our framework and vice-versa. So I want to know how we should start. We thought of several approaches:
1. Start with a plain class
public class Enemy {
public Enemy(int x, int y, int health, int attack, ...) {
...
}
...
}
public class UserDefinedClass extends Enemy {
...
}
2. Start with an abstract class that user-defined enemies have to inherit abstract members
public abstract class Enemy {
public Enemy(int x, int y, int health, int attack, ...) {
...
}
public abstract void draw();
public abstract void destroy();
...
}
public class UserDefinedClass extends Enemy {
...
public void draw() {
...
}
public void destroy() {
...
}
}
3. Create a super ABC (Abstract Base Class) that ALL inherit from
public abstract class VectorEntity {
...
}
public abstract class Enemy extends VectorEntity {
...
}
public class Player extends VectorEntity {
...
}
public class UserDefinedClass extends Enemy {
...
}
Which should I use? Or is there a better way?

Well, it's a bit hard to say for sure without knowing in depth what you're doing, and even then it's rather subjective. However, there are some things to consider which could tell you.
Are they going to actually instantiate an Enemy, or do all enemies really need to be of a derived type? If you're not actually going to be instantiating Enemies rather than derived types, then it should likely be either an interface or an abstract class.
If you're looking to provide actual behavior in your base class, then obviously it needs to be a class rather than an interface.
Methods which need to be there for the API but don't make any sense for you to be providing any implementations for should be abstract.
Methods where it makes good sense to have implementations for them in the base class should have implementations in the base class. And if it doesn't make good sense for them to be overridden, then make them final.
Making classes share a common base class really only makes sense if they're really sharing behavior or you need to be able to treat them all the same somewhere in your code. If they're not really all that similar, then they probably shouldn't share a base class. For instance, if both Enemy and Player are supposed to be displayable, it may make sense to have a common base class which handles their display functionality. But if Enemy were something that was displayable, and Player was a more abstract concept - like the controller of the game - and wasn't displayable, then it probably wouldn't make sense for them to share a base class. In general, it's better to prefer composition rather than inheritance when building classes, so if the classes in question aren't really going to be sharing behavior and don't really have an "is-a" relationship with a common base class, then they shouldn't share a common base class.
Prefer to have your base classes only share methods, not data. In other words, in an inheritance tree, it's best that only the leaves be instantiable. There are various things like equals() which break down when you have base classes with actual data in them. That's not to say that you can't do that - people do it all the time - but it can cause problems and is best avoided if it isn't needed.
Prefer to override abstract methods. Otherwise, in derived classes, you risk not calling the base class' method or totally changing what the method does.
I'm sure that I could come up with more, but without really being familiar with your project, it's bound to be rather generic. Out of the 3 options that you gave, I'd probably go with 2. 3 seems like you'd probably be creating a base class for unrelated classes, and 1 would result in Enemy being instantiatable, which you probably don't need and would definitely make it so that more than the leaves in your inheritance hierarchy would be instantiatable. You'll probably still end up with data in base classes with 2, but you're more likely to only be overriding abstract methods, and you'll have fewer problems with altered behavior in derived classes.

A fourth option would be to use interfaces.
interface Enemy {
public void draw();
. . .
}
If you're just starting out, I would avoid your third option. Let the framework develop a little and see if there's a need for it.

My rule of conduct is that a long as there are more than one class that share the same operations/data/methods/functionality, they should be extensions of the same abstract class.
So, if it was me doing it:
If ALL classes have something in common, have an top-level abstract class that gathers this functionality/fields/data in one place.
If they don't, only those classes that actually have something in common should extend a lower-level abstract class.
If only methods are what the classes will have in common, interfaces can be used as well. However, I always find that sooner or later I see that the classes that implement the interface have the same private fields. At this point, I transform the interface to an abstract class that holds these private fields (to save on lines of code if nothing else).

Just a small answer out of the book "More effective c++" page 271:
"Make base classes abstract that are not at the end of a hierachy". I'm too lazy to give you the whole chapert, but the autor lists some good reasons for that.

Related

When to use interfaces from an oop pov [duplicate]

This question already has answers here:
When to use an interface instead of an abstract class and vice versa?
(26 answers)
Closed 8 years ago.
I have been taught many things about how to structure code. For instance, nouns translate to classes (Eg, class Dog, class Banana). Something that objects have translate to variables inside the class. (Eg, a dog has a name so name would be a variable inside the Dog class.) I've also been taught that abstract nouns translate to abstract classes, eg, ChessPiece would be an abstract class and king, pawn etc would inherit from it.
How do interfaces work like this? I never find myself using interfaces and I want to because I heard that you should design towards an interface.
Interfaces "work like this" such that they enforce a contract to be met amongst its implementer. IOW, the interface says = "you shall do this". So, keeping with your example you might think even "lower" by observing that a ChessPiece is actually a GamePiece in that it inherits a certain amount of behavior that all game pieces have. It may be as simple as...
public interface GamePiece {
void move(int x, int y);
// more behaviors here
}
And you have your abstract class of ChessPiece...
public abstract class ChessPiece implements GamePiece {
// could add more shared stuff here
public abstract void move(int x, int y);
// other stuff can be implemented if needed
}
which the King would extend...
public class King extends ChessPiece {
#Override
public void move(int x, int y) {
// move as the King does
}
}
BUT you can also apply that contract to other game pieces as well. Perhaps you want a CandyLand piece...
public class CandyLandPiece implements GamePiece {
#Override
public void move(int x, int y) {
// move as these pieces do
}
}
I would generally agree with the first paragraph.
On
How do interfaces work like this? I never find myself using interfaces and I want to because I heard that you should design towards an interface.
You probably haven't dealt with large projects in java.
Interfaces are exactly what they sound - definition of a contract with which two java modules can communicate. Abstract classes are interfaces + definition of functionality.
I use interfaces when I think of communication with external module. It should be able to see and use your interface and (probably) nothing else.
Abstract classes are there to avoid repetition in their subclasses, but, as you know, cannot be instantiated, ergo they lack some functionality to be a complete object of the type.
Maybe you should provide a code snippet that can be discussed here.
Think of Interfaces as agreements. A cricket ball and a football for instance can be considered classes. But they follow a common agreement say "Bouncable". Interfaces logically combine classes of different class hierarchies together.
Modified answer as per comment: Bounceable Interface can have a method "bounce". This would in turn imply that all classes that implement Bounceable Interface would definately have to implement "bounce". Logically this sounds correct as well that every Bouncable ball (be it a cricket ball or a football) must be able to bounce.
On the surface, interfaces are very much like classes, except they can't define the methods inside them. It is left upto the implementing class to define the method as they seem fit. Since Java quite sensibly does not allow one class to inherit from multiple classes (multiple inheritance), one class can still implement multiple interfaces to achieve this goal and avoid the pitfalls that come with multiple inheritance.
So you could have a method sound within the interface animal, and every class implementing this interface will have to define method sound in their own custom way. Here's an example,
Suppose you have an interface Animal which has a makesSound method.
class Dog implementing Animal will also have to define makeSound(){//bark}
class Cow implementing Animal will also have to define makeSound(){//Moo}
If you are going to be implementing same functionality for all classes, good idea to extend a class and if you want custom functionality with same name for all classes, good idea to go with an interface. Generally, lean towards an interface as it will allow you the option to extend a class to your current class in the future.

Difference between abstract class with all method abstract and interface?

I had an interview where interviewer asked me first what is the difference between abstract class with all the methods abstract and an interface.
I replied that if it is required to inherit something in the future you will not be able to do it if you have already extended a class.
Then, he stated that it was a situation where one would never have to extend any other class and you have to implement a contract. In this circumstance, which would be better, an abstract class or an interface?
I told him you can use either of them but he was not satisfied. I could not understand why - I believe that is a developer/design choice.
The answer stating that an interface represents a contract is not acceptable.
That's the answer we give to Junior since it may be too complex to clearly figure out the difference between the essence of an abstract class and the essence of an interface without much architecture experience and without reading a lot of classic books about.
Any abstract class with public methods acts as a contract, as well as an interface.
An abstract class that doesn't provide any implementation is in 99% of cases a representation of an object's Role.
An interface represents a Role.
Each object might have several different roles that shouldn't be tied together but composed by the concerned object.
I'm explaining this with this example:
Your interviewer could say:
I have a Robot that can walk and a Human that can walk too.
So based on this case, he asks you: should I extract the walking feature in an abstract base class or in an interface, knowing that the implementations have nothing in common?
You think..."oh I know so: in this case, having one abstract class with an abstract method walk(), then is clearly the same than declaring an interface with the walk() method."
So your answer would surely be: "it's the choice of the developer !".
And it's really not an always valid answer.
Why? Let's see the next expectation:
A Human can eat, but obviously the Robot cannot and even doesn't need.
What if you implemented the walking feature with an abstract class? You would end up with:
public abstract class Biped {
public void abstract walk();
}
public Robot extends Biped {
public void walk() {
//walk at 10km/h speed
}
}
public Human extends Biped {
public void walk() {
//walk at 5km/h speed
}
}
How could you plug the eating feature? You're stuck because you can't implement it in the Biped base class since it would break Liskov Substitution Principle, since a Robot doesn't eat!
And you can't expect Human extending another base class due to the known Java rule.
Of course, you could add a specific Feedable interface only dedicated to Human:
public interface Feedable {
void eat();
}
Signature becomes: public Human extends Biped implements Feedable {
Clearly, it makes no sense and confusing to have one role implemented through a class and the other through an interface.
That's why starting with interface is really preferred whenever we have the choice.
With an interface, we can model Roles easily by composing.
So the final solution would then be:
public interface Walkable {
void abstract walk();
}
public interface Feedable {
void eat();
}
public Robot implements Walkable {
public void walk() {
//walk at 10km/h speed
}
}
public Human implements Walkable, Feedable {
public void walk() {
//walk at 5km/h speed
}
public void eat(){
//...
}
}
Doesn't it remind you the Interface Segregation Principle? ;)
To sum up, if you specify an IS-A relationship, uses an abstract class.
If you realize that you are about to model a Role (let's say a IS-CAPABLE-OF relationship), go with interface.
Here are the differences:
A class can extend exactly abstract class, but can implement any number of interfaces.
An abstract class can have protected, private (does not apply to your question), package, and public methods, but an interface can only have public methods.
An abstract class can have instance variables (often called data members or properties) while an interface can only have static variables.
The answer to the question: "blah never extend blah implement contract blah" is this: "I would use an abstract class if I did needed instance variables and/or non-public methods and otherwise I would use an interface".
Interfaces are the natural way of creating a contract because they force you to implement the methods they define.
Besides that, you can implement as many as you want in the case you want to add new interfaces to your class.
I can't say what your interviewer had in mind, but an interface is more of a "contract" whereas an abstract base class, while it can play that role too, is more geared towards hierarchies or IS-A relationships. E.g. an Apple IS-A Fruit, a Pear IS-A Fruit, etc. But you're right, they could well be used interchangeably for practical purposes in that context, but an OO purist might not want to use an abstract class unless they were expressing IS-A relationship(s).
One thing to keep in mind is be the ability to have diamond inheritance for interfaces.
Consider this interface hierarchy:
interface Base{}
interface Sub1 extends Base{}
interface Sub2 extends Base{}
interface SubSub extends Sub1, Sub2{}
The same wouldn't be possible with abstract classes:
abstract class Base{}
abstract class Sub1 extends Base{}
abstract class Sub2 extends Base{}
// NOT ALLOWED! can only extend one class
// abstract class SubSub extends Sub1, Sub2{}
This is something that would be allowed in C++ (although tricky to get right). I think he might have been fishing for this. In general, this is the ultimate reason why I always try to write interface hierarchies instead of class hierarchies.
For the first situation i'd chose interface over abstract class with all methods abstract as having interface leaves me with option in future for my implementing class to extend some other (abstract) class.
For second scenario, if you really don't want your concrete class to extend any other class and also want to "implement" contract, you can have abstract class with all methods abstract.
I can see such question was already answered. BTW, I would like to share what I consider the best explanation I have read so far.
The bellow text was copied and pasted from Deshmukh, Hanumant. OCP Oracle Certified Professional Java SE 11 Programmer I Exam Fundamentals 1Z0-815: Study guide for passing the OCP Java 11 Developer Certification Part 1 Exam 1Z0-815 (p. 319). Enthuware. Edição do Kindle.
13.2 Distinguish class inheritance from interface inheritance including abstract classes 13.2.1 Difference between Interface and Abstract Class ☝
"What is the difference between an interface and an abstract class" is usually the first question that is asked in a Java "tech-check". While being a simple ice breaker, it also an excellent question to judge a candidate's understanding of OOP. Candidates usually start parroting the technical differences such as an interface cannot have method implementations (which it can, since Java 8), while abstract class can. An interface cannot have static methods (which it can, since Java 8) or instance fields while an abstract class can and so on. All that is correct, but is not really impressive. The fundamental difference between an interface and an abstract class is that an interface defines just the behavior. An interface tells you nothing about the actual object other than how it behaves. An abstract class, on the other hand, defines an object, which in turn, drives the behavior. If you understand this concept everything else about them will fall in place. For example, "movement" is a behavior that is displayed by various kinds of objects such as a Car, a Cat, or a StockPrice. These objects have no commonality except that they move. Saying it the other way round, if you get an object that "moves", you don't get any idea about what kind of an object are you going to deal with. It could be a Car, a Cat, or a StockPrice. If you were to capture this behavior in Java, you would use an interface named Movable with a method named move(). On the other hand, if you talk about Automobile, a picture of an object starts forming in your head immediately. You can sense that an Automobile would be something that would have an engine, would have wheels, and would move. You intuitively know that a StockPrice or a Cat cannot be an Automobile even though they both do move. An abstract class is meant exactly for this purpose, when, once you identify a conceptual object, you do not need to worry about its behavior. The behavior kind of flows automatically. If you create an abstract class named Automobile, you are almost certain that it would have methods such a move, turn, accelerate, or brake. It would have fields for capturing inner details such Engine, Wheels, and Gears. You get all that just by saying the word Automobile. From the above discussion, it should be clear that interfaces and abstract classes are not interchangeable. Even though an abstract class with no non-abstract method looks functionally similar to an interface, both are fundamentally different. If you are capturing a behavior, you must use an interface. If you are capturing a conceptual object, you must use an abstract class.

Why use abstract class and not interface?

For example a real estate builder is constructing an apartment with many flats. All the rooms in the flats have the same design, except the bedroom. The bedroom design is left for the people who would own the flats i.e; the bed Rooms can be of different designs for different flats.
I can achieve this through an abstract class like below:
public abstract class Flat
{
//some properties
public void livingRoom(){
//some code
}
public void kitchen(){
//some code
}
public abstract void bedRoom();
}
}
An implementation class would be as follows:
public class Flat101 extends Flat
{
public void bedRoom() {
System.out.println("This flat has a customized bedroom");
}
}
Alternatively I can use an interface instead of an abstract class to achieve the same purpose like follows:
class Flat
{
public void livingRoom(){
System.out.println("This flat has a living room");
}
public void kitchen(){
System.out.println("This flat has a kitchen");
}
}
interface BedRoomInterface
{
public abstract void bedRoom();
}
public class Flat101 extends Flat implements BedRoomInterface
{
public void bedRoom() {
System.out.println("This flat has a customized bedroom");
}
}
Now the question is : For this why should choose to use an interface (or) why should I choose to use an abstract class?
It depends on your intention or use case. But in general, you should prefer interface over abstract classes (Item 18 in Bloch's Effective Java). Abstract classes are more fragile, because someone may modify the abstract class changing the behavior of other classes extending from it (this is a general statement).
It's more flexible to work with interfaces, because if you have BedroomInterface and LivingRoomInterface, then you can have FlatInterface implementing both interfaces, then Flat101 implementation class implements FlatInterface (instead of extending from Flat then implementing an interface). This seems clearer, and later on you can have ExecutiveFlatInterface which not only have bedroom and living room but also guess room, then Flat102 can implement from it.
Option 2 is to have Flat101 extend from Flat, then Flat implements BedroomInterface and LivingRoomInterface. This really depends on what you want to do and what methods are likely needed.
If you're designing an API that is going to be widely used, you'd use both: an interface to express the contract to be fulfilled by implementing classes, and an abstract class which partially implements that interface and thus permits code re-use.
As an example, consider Java's List: methods in the Collections framework (eg Collections.sort()) are written in terms of the List interface, which is partially implemented by the abstract class AbstractList, which in turn is extended into the concrete implementations LinkedList and ArrayList. LinkedList and ArrayList re-use code from AbstractList, but that does not prevent someone from writing their own completely separate implementation of List and then sorting it using Collections.sort().
That said, in a lot of circumstances this approach can be overkill. If the type hierarchy you're building is only used within a relatively small scope, its generally fine to just use abstract classes. If you decide later on that you want an interface later, its a pretty painless refactoring task to change things.
Abstract classes do have a few advantages:
they allow you to specify abstract methods with package/protected modifiers
they facilitate code re-use
via the use of abstract methods and final methods on the super class they allow you to restrict the manner in which your class is subclassed, which can be useful in a wide variety of circumstances (see also: the Template pattern)
code that references classes is generally easier to follow in an IDE (clicking "open declaration" on an abstract class type parameter is usually more useful than on an interface type parameter)
If you have a class which provides some of the functionality required by derived classes, but each derived class additionally requires differing implementation of other functionality, then an abstract class provides a means of defining the common implementation, while leaving the specific behaviors required by derived classes to be made specific to each derived class.
I feel it is generalization means; an abstract class is most useful if the property and the behaviors of the class are common among a given package or module. One good example is drum brake; as all drum brake works same way holding brakes inside wheel drum so this behavior can be inherited in all class of cars which uses drum brake.
For interface; it is more like specification or contract which force you to implement its speciation. Let’s take an example of model of a building it has all speciation like doors, window, lift ….. But while you implement the model into actual building you we need to keep the window but the internal behavior is decided by (as the widow could be a simple widow or a slider window, the color and material …)
Hope this helps!!
I feel when we need to implement some common functionality and some abstract functionality for multiple class then we should use abstract class. If we see the example of Flat, where we have some common design and some custom design, in such use case it is better to use abstract rather then use interface again to implement custom function and use of abstract as derived class doesn't create an extra instance as normal derived class.
You can not extends more than one class but you can implements more than one interface
If you need to change frequently of your design then abstract class is better because any change happen in abstract class , no force implementation need in sub class. But If any change in interface you have to implement of the implementation class.

What is the main advantage of making a class abstract

Why do we declare a class as abstract? I know it cannot be instantiated, but why give a special keyword for it. Even a 'normal' class will work just as well and can be easily subclassed. so what is the main advantage of making a class abstract?
In abstract class you can implement some method and can make some abstract all your client will have to implement it also. you can provide some common functionality , also you can have some inherited fields and some of the skeleton method here
An abstract class can have abstract methods and "concrete" methods.
The "concrete" methods can use the abstract methods, and can be sure that they are (correct) impelmented at runtime. Because every (not abstract) subclass has to implement them. (And ther will be no instance of the abstract class itselfe).
So it is all about savety! - It makes sure that the programmer who want to subclass an abstract class must implement the abstract method(s).
If you do this only with a normal class then the class, corresponding to the abstract class, would have the (abstract) methods with an empty Implementation, and only a notic to the programmer that he has to override this method.
Of course you can use the concept of abstract classes for other thinks, like create not instanciable classes, but that is not the main point.
I think you misunderstand the point of abstract classes: they provide a partial implementation of some functionality, but not a complete implementation.
You suggested that abstract classes were redundant because you can define incomplete methods using public void methodname(){} -- which is certainly ok. However, let's say your clients inherit from a class defined in such a way, how do they know which methods to override? What happens if they forget to override a method? Now their derived class has an incomplete definition -- you don't want that.
The abstract keyword forces clients to provide implementations for certain methods, otherwise the code won't even compile. In other words, it provides a compile-time guarantee that classes you use or create are fully implemented.
Declaring the class abstract prevents any code from instantiating the class.
This enforces the design guideline to make non-leaf classes abstract.
It allows you to add abstract methods to your superclass (and implementations to the subclasses) later, without affecting any existing clients.
The abstract keyword works even if the non-leaf class does not currently have any abstract methods.
Just a real life example. I have a GUI abstract class that is the parent for all my GUI components. Lets call this AbstractSuperClass. Each of my components that extend AbstractSuperClass need their own implementation of the save function. So the nice thing about making my super class abstract is that I can have an array of type AbstractSuperClass that can hold all of my GUI components. I can then loop over that array and call the save function knowing that each GUI component has its own save method. Since the class is abstract, it forces my subclasses to provide a implementation of the save function.
This is especially useful because when we open up our APIto other programmers, they dont get the source. They just extend the AbstractSuperClass and must provide a save implementation.
It's useful if you want to have a group of classes that inherit the same logical functions.
But in the same time, the class only implements the basic logic, and doesn't contain any real functionality.
You should see it as a skeleton class.
For example, I once made a class with these specifications :
Controls the process of executing a command on another thread, and relays events of that process.
The class itself didn't have any functionality by itself (didn't implement the actual work() function)
So the result is an abstract class, that can be inherited, that already has a built in thread control, which all you need to do is just implement the work() method.
If your class has some default behavior and you want some other behavior to be implemented by the extending classes then you use abstract classes. They cannot be initialized, you can think of abstract classes as a template for the extending classes.
Abstract classes can also call the abstract methods which in result calls extending object's method. Anyways there are lot's of discussions about when to use abstract classes, when to prefer it over an interface. Make a google search, it is an epic discussion :) interfaces vs abstract classes.
You would declare a class as abstract if it makes little to no sense to create an instance of it (you would create instances of subclasses).
public abstract class Shape {
public double calculateArea();
}
public class Square : Shape {
private double side;
double calculateArea() {
return side*side;
}
}
public class Circle: Shape {
private double radius;
double calculateArea() {
return 3.1415 * radius * radius;
}
}
public class MainClass() {
public static void Main() {
Shape myShape = new Square();
system.out.print(myShape.calculateArea());
myShape = new Circle();
}
}
It makes no sense to create an instance of Shape because it doesn't mean anything concrete, its an abstract concept. However, you can have variable of type Shape which allows you to program around the common base-type (though it could be argued that an interface might be better in this situation).
Generally, if there is inheritance, as in a super domain class, with common methods and common implementations in subclasses then look into going with an abstract class, which is not that often, but I do use it.
If you just go with Abstract classes just because there is inheritance, you can run into problems if the code changes a lot. This is detailed very well in the example here: Interfaces vs Abstract Classes in Java, for the different types of domain objects of motors. One of them required a dual powered motor, instead of a specific single type, like asolar powered or battery powered motor. This required multiple subclass implementation methods from both motor types to be used in a single subclass and that is where abstract classes can get messy.
To sum it all up, as a rule you want to define behaviors (what the objects will do) with interfaces and not in Abstract classes. In my thinking, the main advantage for Abstract classes is when the focus from the use case is on an implementation hierarchy and code reuse from subclasses.

How do Java Interfaces simulate multiple inheritance?

I am reading "The Java Tutorial" (for the 2nd time). I just got through the section on Interfaces (again), but still do not understand how Java Interfaces simulate multiple inheritance. Is there a clearer explanation than what is in the book?
Suppose you have 2 kinds of things in your domain : Trucks and Kitchens
Trucks have a driveTo() method and Kitchens a cook() method.
Now suppose Pauli decides to sell pizzas from the back of a delivery truck. He wants a thing where he can driveTo() and cook() with.
In C++ he would use multiple inheritance to do this.
In Java that was considered to be too dangerous so you can inherit from a main class, but you can "inherit" behaviors from interfaces, which are for all intents and purposes abstract classes with no fields or method implementations.
So in Java we tend to implement multiple inheritance using delegations :
Pauli subclasses a truck and adds a kitchen to the truck in a member variable called kitchen. He implements the Kitchen interface by calling kitchen.cook().
class PizzaTruck extends Truck implements Kitchen {
Kitchen kitchen;
public void cook(Food foodItem) {
kitchen.cook(foodItem);
}
}
He is a happy man because he can now do things like ;
pizzaTruck.driveTo(beach);
pizzaTruck.cook(pizzaWithExtraAnchovies);
Ok, this silly story was to make the point that it is no simulation of multiple inheritance, it is real multiple inheritance with the proviso that you can only inherit the contract, only inherit from empty abstract base classes which are called interfaces.
(update: with the coming of default methods interfaces now can also provide some behavior to be inherited)
You're probably confused because you view multiple inheritance locally, in terms of one class inheriting implementation details from multiple parents. This is not possible in Java (and often leads to abuse in languages where it's possible).
Interfaces allow multiple inheritance of types, e.g. a class Waterfowl extends Bird implements Swimmer can be used by other classes as if it were a Bird and as if it were a Swimmer. This is the the deeper meaning of multiple inheritance: allowing one object to act like it belongs to several unrelated different classes at once.
Here is a way to achieve multiple inheritance through interfaces in java.
What to achieve?
class A extends B, C // this is not possible in java directly but can be achieved indirectly.
class B{
public void getValueB(){}
}
class C{
public void getValueC(){}
}
interface cInterface{
public getValueC();
}
class cChild extends C implemets cInterface{
public getValueC(){
// implementation goes here, call the super class's getValueC();
}
}
// Below code is **like** class A extends B, C
class A extends B implements cInterface{
cInterface child = new cChild();
child.getValueC();
}
given the two interfaces below...
interface I1 {
abstract void test(int i);
}
interface I2 {
abstract void test(String s);
}
We can implement both of these using the code below...
public class MultInterfaces implements I1, I2 {
public void test(int i) {
System.out.println("In MultInterfaces.I1.test");
}
public void test(String s) {
System.out.println("In MultInterfaces.I2.test");
}
public static void main(String[] a) {
MultInterfaces t = new MultInterfaces();
t.test(42);
t.test("Hello");
}
}
We CANNOT extend two objects, but we can implement two interfaces.
Interfaces don't simulate multiple inheritance. Java creators considered multiple inheritance wrong, so there is no such thing in Java.
If you want to combine the functionality of two classes into one - use object composition. I.e.
public class Main {
private Component1 component1 = new Component1();
private Component2 component2 = new Component2();
}
And if you want to expose certain methods, define them and let them delegate the call to the corresponding controller.
Here interfaces may come handy - if Component1 implements interface Interface1 and Component2 implements Interface2, you can define
class Main implements Interface1, Interface2
So that you can use objects interchangeably where the context allows it.
It's pretty simple. You can implement more than one interface in a type. So for example, you could have an implementation of List that is also an instance of Deque (and Java does...LinkedList).
You just can't inherit implementations from multiple parents (i.e. extend multiple classes). Declarations (method signatures) are no problem.
You know what, coming from the perspective of a JavaScript dev trying to understand what the heck is going on with this stuff, I'd like to point out a couple things and somebody please tell me what I'm missing here if I'm way off the mark.
Interfaces are really simple. Stupidly, insanely simple. They're as stupidly, insanely simple as people initially think, which is why there are so many duplicate questions on this exact subject because the one reason to use them has been made unclear by people trying to make more of them than they are and there is widespread misuse in every Java server-side code-base I've ever been exposed to.
So, why would you want to use them? Most of the time you wouldn't. You certainly wouldn't want to use them ALL the time as many seem to think. But before I get to when you would, let's talk about what they're NOT.
Interfaces are NOT:
in any way a workaround for any sort of inheritance mechanism that Java lacks. They have nothing to do with inheritance, they never did, and in no way simulate anything inheritance-like.
necessarily something that helps you with stuff you wrote, so much as it helps the other guy write something meant to be interfaced by your stuff.
They really are as simple as you think they are on first glance. People misuse stupidly all the time so it's hard to understand what the point is. It's just validation/testing. Once you've written something conforms to an interface and works, removing that "implements" code won't break anything.
But if you're using interfaces correctly, you wouldn't want to remove it because having it there gives the next developer a tool for writing an access layer for another set of databases or web services that they want the rest of your app to continue using because they know their class will fail until they get the 100% complete-as-expected-interface in place. All interfaces do is validate your class and establish that you have in fact implemented an interface as you promised you would. Nothing more.
They're also portable. By exposing your interface definitions you can give people wanting to use your unexposed code a set of methods to conform to in order for their objects to use it correctly. They don't have to implement the interfaces. They could just jot them down on a piece of notepad paper and double-check that. But with the interface you have more of a guarantee nothing is going to try to work until it has a proper version of the interface in question.
So, any interface not likely to ever be implemented more than once? Completely useless. Multiple-inheritance? Stop reaching for that rainbow. Java avoids them for a reason in the first place and composited/aggregate objects are more flexible in a lot of ways anyway. That's not to say interfaces can't help you model in ways that multiple-inheritance allows but it's really not inheritance in any way shape or form and shouldn't be seen as such. It's just guaranteeing that your code won't work until you've implemented all of the methods you established that you would.
It's not a simulation of multiple inheritance. In java you can't inherit from two classes, but if you implements two interfaces "it seems like you inherited from two different classes" because you can use your class as any of your two intefaces.
For example
interface MyFirstInteface{
void method1();
}
interface MySecondInteface{
void method2();
}
class MyClass implements MyFirstInteface, MySecondInteface{
public void method1(){
//Method 1
}
public void method2(){
//Method 2
}
public static void main(String... args){
MyFirstInterface mfi = new MyClass();
MySecondInterface msi = new MyClass();
}
}
This will work and you can use mfi and msi, it seems like a multi inheritance, but it's not because you don't inherit anything, you just rewrite public methods provided by the interfaces.
You need to be precise:
Java allows multiple inheritance of interface, but only single inheritance of implementation.
You do multiple inheritance of interface in Java like this:
public interface Foo
{
String getX();
}
public interface Bar
{
String getY();
}
public class MultipleInterfaces implements Foo, Bar
{
private Foo foo;
private Bar bar;
public MultipleInterfaces(Foo foo, Bar bar)
{
this.foo = foo;
this.bar = bar;
}
public String getX() { return this.foo.getX(); }
public String getY() { return this.bar.getY(); }
}
Just by the way, the reason why Java does not implement full multiple inheritance is because it creates ambiguities. Suppose you could say "A extends B, C", and then both B and C have a function "void f(int)". Which implementation does A inherit? With Java's approach, you can implement any number of interfaces, but interfaces only declare a signature. So if two interfaces include functions with the same signature, fine, your class must implement a function with that signature. If interfaces you inherit have functions with different signatures, then the functions have nothing to do with each other, so there is no question of a conflict.
I'm not saying this is the only way. C++ implements true multiple inheritance by establishing precedence rules of which implementation wins. But the authors of Java decided to eliminate the ambiguity. Whether because of a philosophical belief that this made for cleaner code, or because they didn't want to do all the extra work, I don't know.
It's not fair to say that interfaces 'simulate' multiple inheritance.
Sure, your type can implement multiple interfaces and act as many different types polymorphically. However, you obviously won't inherit behaviour or implementations under this arrangement.
Generally look at composition where you think you may need multiple inheritance.
OR A potential solution to achieving something multiple inheritance like is the Mixin interface - http://csis.pace.edu/~bergin/patterns/multipleinheritance.html. Use with care!
They don't.
I think that the confusion comes from people believing that implementing an interface constitutes some form of inheritance. It doesn't; the implementation can simply be blank, no behavior is forced by the act or guaranteed through any contract. A typical example is the Clonable-interface, which while alluding to lots of great functionality, which defines so little that's it's essentially useless and potentially dangerous.
What do you inherit by implementing an interface? Bubkes! So in my opinion, stop using the words interface and inheritance in the same sentence. As Michael Borgwardt said, an interface is not a definition but an aspect.
You can actually "inherit" from multiple concrete classes if they implement interfaces themselves. innerclasses help you achieve that:
interface IBird {
public void layEgg();
}
interface IMammal {
public void giveMilk();
}
class Bird implements IBird{
public void layEgg() {
System.out.println("Laying eggs...");
}
}
class Mammal implements IMammal {
public void giveMilk() {
System.out.println("Giving milk...");
}
}
class Platypus implements IMammal, IBird {
private class LayingEggAnimal extends Bird {}
private class GivingMilkAnimal extends Mammal {}
private LayingEggAnimal layingEggAnimal = new LayingEggAnimal();
private GivingMilkAnimal givingMilkAnimal = new GivingMilkAnimal();
#Override
public void layEgg() {
layingEggAnimal.layEgg();
}
#Override
public void giveMilk() {
givingMilkAnimal.giveMilk();
}
}
I'd like to point out something that bit me in the behind, coming from C++ where you can easily inherit many implementations too.
Having a "wide" interface with many methods means that you'll have to implement a lot of methods in your concrete classes and you can't share these easily across implementations.
For instance:
interface Herbivore {
void munch(Vegetable v);
};
interface Carnivore {
void devour(Prey p);
}
interface AllEater : public Herbivore, Carnivore { };
class Fox implements AllEater {
...
};
class Bear implements AllEater {
...
};
In this example, Fox and Bear cannot share a common base implementation for both it's interface methods munch and devour.
If the base implementations look like this, we'd maybe want to use them for Fox and Bear:
class ForestHerbivore implements Herbivore
void munch(Vegetable v) { ... }
};
class ForestCarnivore implements Carnivore
void devour(Prey p) { ... }
};
But we can't inherit both of these. The base implementations need to be member variables in the class and methods defined can forward to that. I.e:
class Fox implements AllEater {
private ForestHerbivore m_herbivore;
private ForestCarnivore m_carnivore;
void munch(Vegetable v) { m_herbivore.munch(v); }
void devour(Prey p) { m_carnivore.devour(p); }
}
This gets unwieldy if interfaces grow (i.e. more than 5-10 methods...)
A better approach is to define an interface as an aggregation of interfaces:
interface AllEater {
Herbivore asHerbivore();
Carnivore asCarnivore();
}
This means that Fox and Bear only has to implement these two methods, and the interfaces and base classes can grow independetly of the aggregate AllEater interface that concerns the implementing classes.
Less coupling this way, if it works for your app.
I don't think they do.
Inheritance is specifically an implementation-oriented relationship between implementations. Interfaces do not provide any implementation information at all, but instead define a type. To have inheritance, you need to specifically inherit some behaviors or attributes from a parent class.
I believe there is a question here somewhere specifically about the role of interfaces and multiple inheritance, but I can't find it now...
There's really no simulation of multiple inheritance in Java.
People will sometimes say that you can simulate multiple inheritance using Interfaces because you can implement more than one interface per class, and then use composition (rather than inheritance) in your class to achieve the behaviors of the multiple classes that you were trying to inherit from to begin with.
If it makes sense in your object model, you can of course inherit from one class and implement 1 or more interfaces as well.
There are cases where multiple-inheritance turns to be very handy and difficult to replace with interfaces without writing more code. For example, there are Android apps that use classes derived from Activity and others from FragmentActivity in the same app. If you have a particular feature you want to share in a common class, in Java you will have to duplicate code instead of let child classes of Activity and FragmentsActivity derive from the same SharedFeature class. And the poor implementation of generics in Java doesn't help either because writing the following is illegal:
public class SharedFeature<T> extends <T extends Activity>
...
...
There is no support for multiple inheritance in java.
This story of supporting multiple inheritance using interface is what we developers cooked up. Interface gives flexibility than concrete classes and we have option to implement multiple interface using single class. This is by agreement we are adhering to two blueprints to create a class.
This is trying to get closer to multiple inheritance. What we do is implement multiple interface, here we are not extending (inheriting) anything. The implementing class is the one that is going to add the properties and behavior. It is not getting the implementation free from the parent classes. I would simply say, there is no support for multiple inheritance in java.
No, Java does not support multiple inheritance.
Neither using class nor using interface. Refer to this link for more info
https://devsuyed.wordpress.com/2016/07/21/does-java-support-multiple-inheritance
I also have to say that Java doesn't support multiple inheritance.
You have to differentiate the meaning between extends and implements keywords in Java. If we use extends, we are actually inheriting the class after that keyword. But, in order to make everything simple, we can't use extends more than once. But you can implement as many Interfaces as you wish.
If you implement an interface, there's a zero chance that you will miss the implementation of all the methods in each interface (Exception: default implementations of interface methods introduced in Java 8) So, you are now fully aware of what is happening with the things that you have embedded to your fresh class.
Why Java doesn't allow multiple inheritance is actually, multiple inheritance makes the code somewhat complex. Sometimes, two methods of parent classes might conflict due to having the same signatures. But if you are forced to implement all the methods manually, you will get the full understanding about what's going on, as I mentioned above. It makes your code more understandable to you.
If you need more info on Java interfaces, check out this article, http://www.geek-programmer.com/introduction-to-java-interfaces/
Between two Java class multiple Inheritance directly is not possible. In this case java recommend Use to interface and declare method inside interface and implement method with Child class.
interface ParentOne{
public String parentOneFunction();
}
interface ParentTwo{
public String parentTwoFunction();
}
class Child implements ParentOne,ParentTwo{
#Override
public String parentOneFunction() {
return "Parent One Finction";
}
#Override
public String parentTwoFunction() {
return "Parent Two Function";
}
public String childFunction(){
return "Child Function";
}
}
public class MultipleInheritanceClass {
public static void main(String[] args) {
Child ch = new Child();
System.out.println(ch.parentOneFunction());
System.out.println(ch.parentTwoFunction());
System.out.println(ch.childFunction());
}
}

Categories