abstract class CAR
fuelUp () { // implemented }
/ \
interface SPORTER interface TRUCK
driveFast (); moveLoad ();
Is there a way in Java I can get
a class ESTATE that has
the implementation fuelUp of CAR
and also must implement driveFast AND moveLoad?
Extending from multiple classes is not possible and making CAR an interface does not give me an implementation in CAR.
Your Java class can only extend 1 parent class, but it can implement multiple interfaces
Your class definition would be as follows:
class ESTATE extends CAR implements SPORTER, TRUCK {}
For more help, see:
https://stackoverflow.com/a/21263662/4889267
As already identified, you can extend one class and implement multiple interfaces. And in Java 8+, those interfaces can have default implementations.
But to add to this, you can also have various implementations of SPORTER, for instance. You could make use of the SporterAlpha implementation through composition.
class Foo extends Car implements Sporter {
private SporterAlpha sporterAlpha;
public int sporterMethodA(int arg1) { return sporterAlpha.sporterMethodA(arg1); }
}
Repeat as necessary to expose all the SporterAlpha methods necessary.
Thus, you can:
Inherit from no more than one superclass
Implement as many interfaces as necessary
Use default implementations on your interfaces with Java 8+
Use composition as appropriate
Related
What is the type of a class if it implements more than one interface?
For example if the class Example implements Interface1 doesExample become of type Interface1? If so what happens if it also implements Interface2. What type is class Example then?
The phrase "become of type interface1" is not clear.
In OO design, a class is supposed to represent a particular "object" or "thing" in your problem domain. If you're writing a system to model vehicles on highways, you might have classes (or interfaces) for "vehicle", "road", etc.
Let's say a part of the system also dealt with commercial vehicles; taxes or something. So there might be a class of "vehicle" and an interface of "CommercialVehicle", with the latter providing methods to get attributes connected with road taxes for the vehicle. Not all Vehicles would be CommercialVehicles, but some of them would implement that interface.
An object of type Vehicle might or might not implement that interface. IF it does implement the interface, that guarantees that it has the associated methods. You can use the "instanceof" operator to determine whether a particular object implements an interface or not.
But I'm not sure what you mean by "become of type interface", so I'm not sure how to answer that question.
Implementing is for interfaces. Extending is for classes.
In Java, you can implement many interfaces, but extend only one.
If you extend a class, you don't become anything, but you do inherit its members (fields, methods, subclasses).
As per your (vague) question, let's assume:
public interface Interface1 {
void myMethod(Interface1 other); // using public is redundant in interfaces
}
public class Example implements Interface1, Interface2 { ... }
Then Example is of type Example (...), and when I need to implement the methods in the interface then:
public void myMethod(Interface1 myObject) {
Example myClass = (Example)myObject;
}
I need to cast to use the methods from Example.
In production code I often see classes defined as follows:
public interface SomeComponent { // Some methods }
public class SomeComponentImpl implements SomeComponent { // Some methods}
public interface SomeComponentV2 extends SomeComponent { // Some methods }
public class SomeComponentV2Impl extends SomeComponentImpl implements SomeComponent { // Some methods }
Why in this case we want to separate the interface and its implementation?
Or put it this way, why is it bad to simply have one base class, and let V2 extend/override V1 as follows:
public class SomeComponent { // Some methods }
public class SomeComponentV2 extends SomeComponent
{
// Override methods for reimplementation
// Add new methods for new features.
}
It is a good practice to separate the interface and the implementation of a class because you can easily swap out classes.
Imagine you want to test a application which depends on a web-service which bills you for every request. In addition to have a class which performs real requests to this web-service, you could build a class which implements the same interface but returns fake data to avoid generating costs for every request.
Every time you inherit from a base-class there is a chance that you inherit behaviour you simply don't want to inherit. An interface is a pure contract and gives you the freedom to let you choose a base-class independently of the described advantage.
Separating interface from implementation allows to fully use polymorphism.
In this way SomeComponentV2Impl will have 3 types - own, base class, and interface.
Here you may just use only the interface without caring about it's implementation in further classes. For example:
public void methodInOuterClass(SomeComponent smCmp){
smCmp.runInterfaceMethods();
}
[Edit: this question appeared in OP question before edites]
Why do we dont use one base class for them all?
Because SomeComponentV2Impl is distinguish from SomeComponentImpl.
But if they implement same interface, you will be able to call their implementation from the interface's refference.
I want to have a Class object, but I want to force whatever class it represents to extend class A and also class B.
I can do
<T extends ClassA & ClassB>
but it is not possible to extend from both classes, Is there a way to do this?
In java you cannot have a class which extends from two classes, since it doesn't support multiple inheritance. What you can have, is something like so:
public class A
...
public class B extends A
...
public class C extends B
...
In your generic signature, you can then specify that T must extend C: <T extends C>.
You could give a look at Default Methods (if you are working with Java 8), which essentially are methods declared within interfaces, and in Java, a class can implement multiple interfaces.
A simple way for this problem is inheritance.
public class A { // some codes }
public class B extends A { }
<T extends A>
Java does not have multiple inheritance as a design decision, but you may implement multiple interfaces.
As of Java 8 these interfaces may have implementations.
To use multiple classes there are other patterns:
If the parent classes are purely intended for that child class, but handle entirely different aspects, and were therefore separated, place them in a single artificial hierarchy. I admit to doing this once.
Use delegation; duplicate the API and delegate.
Use a lookup/discovery mechanism for very dynamic behaviour.
public T lookup(Class klazz);
This would need an API change, but uncouples classes, and is dynamic.
What I mean is:
interface B {...}
interface A extends B {...} // allowed
interface A implements B {...} // not allowed
I googled it and I found this:
implements denotes defining an implementation for the methods of an interface. However interfaces have no implementation so that's not possible.
However, interface is an 100% abstract class, and an abstract class can implement interfaces (100% abstract class) without implement its methods. What is the problem when it is defining as "interface" ?
In details,
interface A {
void methodA();
}
abstract class B implements A {} // we may not implement methodA() but allowed
class C extends B {
void methodA(){}
}
interface B implements A {} // not allowed.
//however, interface B = %100 abstract class B
implements means implementation, when interface is meant to declare just to provide interface not for implementation.
A 100% abstract class is functionally equivalent to an interface but it can also have implementation if you wish (in this case it won't remain 100% abstract), so from the JVM's perspective they are different things.
Also the member variable in a 100% abstract class can have any access qualifier, where in an interface they are implicitly public static final.
implements means a behaviour will be defined for abstract methods (except for abstract classes obviously), you define the implementation.
extends means that a behaviour is inherited.
With interfaces it is possible to say that one interface should have that the same behaviour as another, there is not even an actual implementation. That's why it makes more sense for an interface to extends another interface instead of implementing it.
On a side note, remember that even if an abstract class can define abstract methods (the sane way an interface does), it is still a class and still has to be inherited (extended) and not implemented.
Conceptually there are the two "domains" classes and interfaces. Inside these domains you are always extending, only a class implements an interface, which is kind of "crossing the border". So basically "extends" for interfaces mirrors the behavior for classes. At least I think this is the logic behind. It seems than not everybody agrees with this kind of logic (I find it a little bit contrived myself), and in fact there is no technical reason to have two different keywords at all.
However, interface is 100% abstract class and abstract class can
implements interface(100% abstract class) without implement its
methods. What is the problem when it is defining as "interface" ?
This is simply a matter of convention. The writers of the java language decided that "extends" is the best way to describe this relationship, so that's what we all use.
In general, even though an interface is "a 100% abstract class," we don't think about them that way. We usually think about interfaces as a promise to implement certain key methods rather than a class to derive from. And so we tend to use different language for interfaces than for classes.
As others state, there are good reasons for choosing "extends" over "implements."
Hope this will help you a little what I have learned in oops (core java) during my college.
Implements denotes defining an implementation for the methods of an interface. However interfaces have no implementation so that's not possible. An interface can however extend another interface, which means it can add more methods and inherit its type.
Here is an example below, this is my understanding and what I have learnt in oops.
interface ParentInterface{
void myMethod();
}
interface SubInterface extends ParentInterface{
void anotherMethod();
}
and keep one thing in a mind one interface can only extend another interface and if you want to define it's function on some class then only a interface in implemented eg below
public interface Dog
{
public boolean Barks();
public boolean isGoldenRetriever();
}
Now, if a class were to implement this interface, this is what it would look like:
public class SomeClass implements Dog
{
public boolean Barks{
// method definition here
}
public boolean isGoldenRetriever{
// method definition here
}
}
and if a abstract class has some abstract function define and declare and you want to define those function or you can say implement those function then you suppose to extends that class because abstract class can only be extended. here is example below.
public abstract class MyAbstractClass {
public abstract void abstractMethod();
}
Here is an example subclass of MyAbstractClass:
public class MySubClass extends MyAbstractClass {
public void abstractMethod() {
System.out.println("My method implementation");
}
}
Interface is like an abstraction that is not providing any functionality. Hence It does not 'implement' but extend the other abstractions or interfaces.
Interface is the class that contains an abstract method that cannot create any object.Since Interface cannot create the object and its not a pure class, Its no worth implementing it.
This question already has answers here:
Interface vs Abstract Class (general OO)
(36 answers)
Abstract class vs Interface in Java
(15 answers)
Closed 2 years ago.
Please tell me situation where interface is better than abstract class in Java
I think you have misunderstood the real meaning of interface and abstract class.
Interface is programming structure where you define your functions/services that you want to expose to public or other modules. Kind of a contract where you promise that you are providing some functionalities or services, but hiding the implementation so that implementation can be changed without affecting your contract.
Abstract class is a partially implemented class and it has no real meaning other than serving as a parent for multiple child classes those with real meaning. Abstract class is special parent class that provides default functionalities to multiple child classes. it is created as abstract because of unavailability of suitable concrete parent class.
In a good design, you should always create an interface. But abstract class is optional. If you can not find a concrete parent class, create an abstract class and implement the interface then provide default implementations for those interface functions (if possible) otherwise mark them as abstract functions and leave the implementation to the child classes.
A class can implement multiple interfaces, but it can only extend one abstract class.
Interfaces allow the creation of proxies that encapsulate a concrete class. This is used extensively by frameworks in order to intercept method calls to the concrete class (e.g., for starting a transaction before the method is executed or to write to the log).
Use an interface when you don't need to provide any default implementations.
Here is a nice link comparing the two: Interface vs. Abstract Class
You can only have one direct abstract superclass. Therefore, interfaces are useful if you need to expose two or more interfaces.
Java doesn't have multiple inheritance; thus, you cannot have a class that implements two abstract classes at once. For instance, if you want a MouseListener and an ActionListener in a same class, you have to do it the interface way.
An interface is better than a abstract class when you want multiple classes to implement that interface and when you don't have to inherit default behavior.
In order to provide WebServices or do JMock tests you dont need the actual implementation, you just need an interface definition. Think about it, there is no need to return the implementation to a third party when all they need to do is call your API.
When you need to implements in any class because interface can be implements in any class or interface but abstract class cant do that e.g. in Applet always Applet class extend in our Applet Application in this case we cant extend the abstract class.
Abstract Class : Define or Declare a method which is more important. Example:
Vehicle must have shape and engine. So we put this behaviour is in Abstract class.
abstract class Vehicle {
abstract void shape();
abstract void engine();
}
Interface Class : Other than that properties like move, honk, etc. So interfaces that provide additional behaviour to your concrete class.
interface Honk{
void honk();
}
interface moveable{
void move();
}
class Car extends Vehicle implements Moveable {
#Override
void shape() {
System.out.println("car's shape");
}
#Override
void Engine() {
System.out.println("car's engine");
}
#Override
void move() {
System.out.println("car's can move");
}
}
But I didn't implements Honk behaviour. If you want you can implements multiple interfaces.