Java inheritance hierarchy -- implementing an interface a super-class is implementing - java

When I extend a class, say class A in class B, i'm implementing all interfaces that class A implements.
In the following,
interface INTF { ... }
class A implements INTF { ... }
class B extends A { .... }
class B, being a descendant of class A, is implementing INTF.
So, what's my gain in declaring class B as
class B extends A implements INTF { .... }
?
//===========================
EDIT:
Java APIs are doing this. Eg.:
public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V> { ...
what for ?
TIA

There is no difference if your sub class restates that it implements an interface.But there is a huge gain when it comes to Reflection API.I have personally faced it..
When you call B.class.getInterfaces() ,it returns a Class[] containing only those interfaces explicitly declared by the class and not its superclasses,although in reality it is implementing interfaces which are implemented by its superclasses.
To solve it,you need to recursively call the super class and get all the interfaces implemented.Declaring an interface explicitly in your sub class will help you in this case

You don't have to re-declare the interface again. However, there will be differences if you using Java reflections - B.class.getInterfaces().
If you don't re-declare the interface again. B.class.getInterfaces() -- return zero interface
If you re-declare the interface B.class.getInterfaces() - Return one interface
So deciding to re-declare the interface again or Not depending on how you use java reflections on it. For most case, we don't re-declare it again.

You don't have to specify the interface again. You could specify all the implemented methods again, but you don't have to do that either.
If A changes the interface it implements in future B might not need to know about it.

It makes no difference whether you specify that B implements INTF or not, since it must implement it anyway, since A is implementing it.
I'm not sure why Java APIs are doing it. I'm assuming they simply want to make it more clear to the user of LinkedHashMap that it implements Map (otherwise the user would have to look at the declaration of HashMap to find this out).

Related

Enforcing the implementer of an interface to be an enum

I would like to store a type called App inside a set. App needs to be an enum that implements the App interface.
Set<App> myApps;
I have defined the interface like so...
interface App<T extends Enum<T>> {}
This is almost working, for example, you cannot do this...
class MyClass implements Application<MyClass> {}
However, you can do this...
enum MyEnum implements Application<MyEnum> {}
class Myclass implements Application<MyEnum> {}
Which is wrong. I only want enums to be able to implement this interface, how can I enforce this?
Define a method that allows you to add Elements into the set, BUT use a constraint for that parameter...
public <E extends Enum<E> & IMyInterface> void addToSet(final E value) { }
now after that
addToSet(MyEnum.K) will compile
but
addToSet(new Myclass()) will NOT compile
AFAIK it is not possible to enforce an implementor of an interface to have certain properties such as being an enum.
However, depending on your code and how you use that interface you can make it hard for someone not to make the implementor an enum:
Require T to implement App<T> as well to prevent passing any enum to the class declaration (i.e. App<T extends Enum<T> & App<T>>)
Use additional boundaries when possible (see ΦXocę 웃 Пepeúpa's answer)
Add methods that are already implemented by Enum such as name(), ordinal(), getDeclaringClass() etc.
Let App<T ...> extend Comparable<T>.
When possible call getClass().isEnum() to check that property at runtime. This is not ideal but there are similar solution's that are commonly used such as Collections.unmodifiableSet().

Do Abstract classes need to implement an entire interface in java 7?

I need a group of different classes to implement a certain interface. However, a lot of those classes, but not all of them, need a same implementation for some of the methodes defined in the interface. I was wondering if I could make an abstract class implement the interface and only create the methods that are the same for those classes?
For example, I have interface A:
public interface A{
public returnType method1(){};
public returnType method2(){};
}
Can I do this:
public abstract class AbstractPartialA implements A{
#Override
public returnType method1(){
implementation
}
}
and than have the classes extending from this Abstract class implement the remaining methods that are required to fulfill the interface?
Yes, you can, that is the exact purpose of abstract classes.
Do Abstract classes need to implement an entire interface in java 7?
And the answer is " NO ". Abstract class can implement entire interface or it can implement only some methods of an interface.
Case-1
If it implements entire interface and is still declared as 'abstract', it means we don't want other(people who are going to use our class) to create object for our class
Example of such class is HttpServlet in javax.servlet.http . Here HttpServlet class doesn't have any abstract method, but still it is declared as 'abstract'
Case-2
Simple, if the class doesn't implement any one of the method of an interface, then it is declared as 'abstract'. Now it will be the responsibility of the other class which extends the abstract class to provide the implementation of such method which is not implemented by 'abstract class'
You can, and when you try to extend from AbstractPartialA Java will ask you to:
Implement all methods declared in implemented interfaces and not implemented
Implement all methods declared as abstract in superclasses
Remember that a class is considered to implement all interfaces implemented by its superclasses, not just the ones specifically written after the implements keyword in this class' declaration. This applies both to the types of the class (and thus the types of its references) and to the methods it is required to implement.

Why doesn't interfaces implement methods and override them?

I already read the post of research effort required to post a SO question. I am ashamed again to post this question to a pile of million questions. But I still don't get the idea of interfaces in java. They have unimplemented methods and then defined for every class in which they are implemented. I searched about it. Interfaces were used to support multiple inheritance in java and also to avoid (Deadly) Diamond Death of inheritance. I also came across Composition vs Inheritance and that inheritance is not for code reuse and its for polymorphism. So when I have a common code as a class to extend it will not be supported due to multiple inheritance which gives the option to use Interfaces(Correct me if I am wrong). I also came across that its not possible in most cases to define a generic implementation. So what is the problem in having a common definition (not a perfect generic implementation) of the interface method and then Override it wherever necessary and why doesn't java support it. Eg. When I have 100 classes that implements an interface 70 of them have a common implementation while others have different implementation. Why do I have to define the common method in interface over 70 classes and why can't I define them in Interface and then override them in other 30 classes which saves me from using same code in 70 classes. Is my understanding of interfaces wrong?
First, an interface in Java (as of Java 7) has no code. It's a mere definition, a contract a class must fulfill.
So what is the problem in having a common definition (not a perfect
generic implementation) of the interface method and then Override it
wherever necessary and why doesn't java support it
Yes you can do that in Java, just not with interfaces only. Let's suppose I want from this Example interface to have a default implementation for method1 but leave method2 unimplemented:
interface Example {
public void method1();
public String method2(final int parameter);
}
abstract class AbstractExampleImpl implements Example {
#Override
public void method1() {
// Implement
}
}
Now classes that want to use this method1 default implementation can just extend AbstractExampleImpl. This is more flexible than implementing code in the interface because if you do so, then all classes are bound to that implementation which you might not want. This is the advantage of interfaces: being able to reference a certain behavior (contract) without having to know how the class actually implements this, for example:
List<String> aList = MyListFactory.getNewList();
MyListFactory.getNewList() can return any object implementing List, our code manipulating aList doesn't care at all because it's based on the interface.
What if the class that uses interface already is a Sub-class. Then we
can't use Abstract class as multiple inheritance is not supported
I guess you mean this situation:
class AnotherClass extends AnotherBaseClass
and you want to extend AbstractExampleImpl as well. Yes, in this case, it's not possible to make AnotherClass extend AbstractExampleImpl, but you can write a wrapped inner-class that does this, for example:
class AnotherClass extends AnotherBaseClass implements Example {
private class InnerExampleImpl extends AbstractExampleImpl {
// Here you have AbstractExampleImpl's implementation of method1
}
}
Then you can just internally make all Example methods being actually implemented by InnerExampleImpl by calling its methods.
Is it necessary to have the interface in AnotherClass?
I guess you mean AnotherClass implements Example. Well, this is what you wanted: have AnotherClass implement Example with some default implementation as well as extend another class, or I understood you wrong. Since you cannot extend more than one class, you have to implement the interface so you can do
final Example anotherClass = new AnotherClass();
Otherwise this will not be possible.
Also for every class that implements an interface do I have to design
an inner class?
No, it doesn't have to be an inner class, that was just an example. If you want multiple other classes have this default Example implementation, you can just write a separate class and wrap it inside all the classes you want.
class DefaultExampleImpl implements Example {
// Implements the methods
}
class YourClass extends YetAnotherClass implements Example {
private Example example = new DefaultClassImpl();
#Override
public void method1() {
this.example.method1();
}
#Override
public String method2(final int parameter) {
return this.example.method2(parameter);
}
}
You can create an abstract class to implement that interface, and make your those classes inherit that abstract class, that should be what you want.
A non abstract class that implements and interface needs to implement all the methods from the interface. A abstract class doesn't have to implement all the methods but cannot initiated. If you create abstract class in your example that implements all the interface methods except one. The classes that extend from these abstract class just have to implement the one not already implemented method.
The Java interfaces could have been called contracts instead to better convey their intent. The declarer promise to provide some functionality, and the using code is guaranteed that the object provides that functionality.
This is a powerful concept and is decoupled from how that functionality is provided where Java is a bit limited and you are not the first to notice that. I have personally found that it is hard to provide "perfect" implementations which just need a subclass or two to be usable in a given situation. Swing uses adapters to provide empty implementations which can then be overrides as needed and that may be the technique you are looking for.
The idea of the interface is to create a series of methods that are abstract enough to be used by different classes that implement them. The concept is based on the DRY principle (Don't repeat yourself) the interface allows you to have methods like run() that are abstract enough to be usuable for a game loop, a players ability to run,
You should understand the funda of interface first. Which is
It is use to provide tight coupling means tight encapsulation
It helps us to hide our code from the external environment i.e. from other class
Interface should have only definition and data which is constant
It provide facility to class open for extension. Hence it cannot be replace by the any other class in java otherwise that class will become close for extension. which means class will not be able to extend any other class.
I think you are struggling with the concept of Object Oriented Design more than anything. In your example above where you state you have 100 classes and 70 of them have the same method implementation (which I would be stunned by). So given an interface like this:
public interface Printable
{
void print();
}
and two classes that have the "same" implementation of print
public class First implements Printable
{
public void print()
{
System.out.println("Hi");
}
}
public class Second implements Printable
{
public void print()
{
System.out.println("Hi");
}
}
you would instead want to do this:
public abstract class DefaultPrinter implements Printable
{
public void print()
{
System.out.println("Hi");
}
}
now for First and Second
public class First extends DefaultPrinter
{
}
public class Second extends DefaultPrinter
{
}
Now both of these are still Printable . Now this is where it gets very important to understand how to properly design object hierarchies. If something IS NOT a DefaultPrinter YOU CANNOT AND SHOULD NOT make the new class extend DefaultPrinter

Few Questions over abstract class and interface in java?

What is use of an abstract class implementing an interface? In which
scenario would we implement.
Why would you choose Abstract class over interface? If an class
extends an Abstract class, should we implement all the methods in
the Abstract Class. If an class implements an Interface should we
implement all the methods too.
Why was abstract class or interface pattern introduced? What is the
use of them? Does it deal anything in the way object is getting
instantiated or the way it behaves?
If an abstract class has a static method declared, then can we
instantiate that class?
I was asked these questions, though my answers were not clear... i would like to know from people here?
1&2) You can use interfaces and abstract classes together -- the interface can provide a definition of behavior, and the abstract class provides partial implementation, the subclasses provide full implementation.
3) Interfaces and abstract classes are concepts. The java language designers decided to provide language features to realize the concepts.
4) An instance of an abstract class can never be instantiated. A static method on an abstract class can be invoked normally, remember static methods are invoked by referencing the class, not an instance of the class.
some psuedocode
abstract class Base {
abstract void doSomething(); // subclass provides implementation
protected helper() {
// doSomething implementation in subclass can use helper
}
}
On Abstract classes and Interfaces
Abstract classes defines a partial representation of some entity, that is common to every extending class but that must be completed by inheritance. So, every inheriting class comprehends all the properties defined in every parent classes.
Interfaces provide a behavior to a given class, and allow to simulate something similar to multiple inheritance. Since you can implement multiple interfaces in a class, you can make that class adopt the behavior of every implementing interface, and all together.
Classical example:
Abstract class: Animal Represents an animal in an abstract way. Each animal should extend this class to adopt all the implications of "being" an animal.
Abstract class: Mammal extends Animal The mammal is an Animal and inherits all the properties that are common to every mammal.
Some mammals are carnivorous and some herbivorous. These are different behaviors for the same type of animal, so here they come the interfaces.
Interface: Carnivorous Defines the properties a carnivore animal should have.
Interface: Herbivorous Defines the properties a herbivore animal should have.
Every mammal should breath air. This is another behavior, that is common to every mammal.
Interface AirBreathing Defines the properties for air-breathing animal
So. You have these two mammals: Wolves and Manatees. Both have to breath air, but wolves are carnivorous and manatees herbivorous.
Class Wolf extends Mammals implements AirBreathing, Carnivorous
Class Wolf extends Mammals implements AirBreathing, Herbivorous
Implementation details
1) Every abstract method defined in an abstract class, must be implemented somewhere "in the road" of inheritance until a final class is reached. This means that when a final class is implemented it must implement or inherit implementations of every abstract method inherited from parent classes.
2) Yes, you can define static methods in abstract classes. You can call static method from the abstract class as AbstractClass.staticMethod(), but you can't ever instantiate an abstract class.
3) Classes implementing interfaces, must implement every method defined by the interface.
Hope this helps.
What is use of an abstract class implementing an interface? In which scenario would we implement?.
One important use is to provide a skeletal implementation reducing the effort needed to implement the interface. An example of this is AbstractCollection<E> which implements the Collection<E> interface in the Java Collections Framework.
Why would you choose Abstract class over interface?
When I want to provide an implementation for some parts of the class's behaviour.
If a class extends an abstract class, should we implement all the methods in the abstract
Class. If an class implements an interface should we implement all the methods too.
Concrete classes must completely implement the abstract interface. You have no choice but to implement all methods. This is because whenever you implement an interface or extend an abstract class with a concrete implementation, you're declaring that the concrete class fully describes the interface's behavior.
Of course abstract extensions don't have to implement the interface completely i.e. abstract extensions of interfaces / abstract classes aren't forced to implement the interface in entirety.
Why was abstract class or interface pattern introduced? What is the use of them? Does it deal anything in the way object is getting instantiated or the way it behaves?
Interfaces describe the behavior of types. Since all implementations must completely describe the behavior enforced by the interface, they allow for polymorphism.
Canonical Collections Framework example:
The List<E> interface describes how a list of objects may behave. It describes the add, remove, get and set operations to name a few.
2.ArrayList<E> and LinkedList<E> are two concrete implementations of the List<E> interface.
3.Thus it's guaranteed that both of them behave like a List<E> and more specifically have concrete implementations of the add, remove, get and set operations to name a few.
4.Also since both of them implement the same interface, more specifically, both of them behave like a List<E>, I can use them, wherever I need to use a List<E>.
5.This allows for statements like these :
List<String> names = new ArrayList<String>();
List<String> queue = new LinkedList<String>();
showList(names);
showList(queue);
void showList(List<String> list) {
for(String s : list)
System.out.println(s);
}
This is a very simple example of polymorphism in action. The showList(List<String> list) methods accepts and happily iterates over names and queues because both of them implement the same interface and it can be sure of it's behaviour.
I have just completed my studies and joined a firm. So might be possible i may not be able to give you good example but yes in broad sense they gonna work and they are effective...
the most important reason for using interface is to create a common behavior in related classes. Wonderfull example is collection framework. Collection is a interface that ensure whatever the classes that represents collection of some objects then it should compulsory implement all the methods of collection(else they wont be a collection, also note that collection is a behavior) and now this interface is further implemented by other interface list so all the collection which are of type list implement this(here we have specialize the behavior of collection(by adding some method), note that list is also a behavior). Now we want a class which represents nothing but a collection of array as linked list so we implemented all the methods of list(which ultimately have collection method).
Now come to abstract class, consider the example of Number class in java its a abstract class which implements serializable interface since it has to show serialized behavior. Also note that Number represents some physical entity, so it should be a abstract class. Abstract because from it we cant conclude to exact object. While serializable is a behavior hence interface.
Thats what i could deliver to you and thats what i learned from my basic knowledge. But always remember oops differ people to people. See your encapsulation implement abstraction example as well. So everything depends on you.

When to use extends and when to use interface?

We can extend a class but we cannot implement a class. We can implement an interface, but cannot extend an interface.
In what cases should we be using extends?
extends is used for either extending a base class:
class ClassX extends ClassY {
...
}
or extending an interface:
interface InterfaceA extends InterfaceB {
...
}
Note that interfaces cannot implement other interfaces (most likely because they have no implementation).
Java doesn't impose any naming conventions for classes vs. interfaces (in contrast to IFoo for interfaces in the .NET world) and instead uses the difference between extends and implements to signify the difference to the programmer:
class ClassA extends ClassB implements InterfaceC, InterfaceD {
...
}
Here you can clearly see that you're building upon an existing implementation in ClassB and also implement the methods from two interfaces.
Is a matter of uses. Interfaces can be used as a contract with your application and then base classes can be use to extend that interface, so it is loosely couple.
Take for example Injection Dependency pattern:
You first write a contract:
public interface IProductRepository
{
IList<T> GetAllProducts();
}
Then you extend your contract with a base class:
public abstract BaseProductRepository : IProductRepository
{
public IList<T> GetAllProducts()
{ //Implementation }
}
Now you have the option to extend base into two or more concrete classes:
public class InternetProductRepository extends BaseProductRepository;
public class StoreProductRepository extends BaseProductRepository;
I hope this small examples clears the differences between extend and Implement. sorry that I did not use java for the example but is all OO, so I think you will get the point.
Thanks for reading, Geo
I did not complete the code for injection dependency pattern but the idea is there, is also well documented on the net. Let me know if you have any questions.
Actually, you can extend an interface - in the case where you're defining another interface.
There are lots of quasi-religious arguments about this issue and I doubt there's a clear right answer, but for what it's worth here's my take on things. Use subclassing (i.e. extends), when your various classes provide the same sort of functionality, and have some implementation details in common. Use interface implementation, in order to signal that your classes provide some particular functionality (as specified by the interface).
Note that the two are not mutually exclusive; in fact if a superclass implements an interface, then any subclasses will also be considered to implement that interface.
In Java there is no multiple inheritance, so that a (sub)class can only have one parent class, and subclassing should be considered carefully so as to choose an appropriate parent if any at all; choosing a parent that reflects just a small amount of the class' abilities is likely to end in frustration later if there are other sensible parent classes. So for example, having an AbstractSQLExecutor with SQL Server and Oracle subclasses makes a lot of sense; but having a FileUtils parent class with some utility methods in, and then subclassing that all over the place in order to inherit that functionality, is a bad idea (in this case you should likely declare the helper methods static, or hold a reference to a FileUtils instance, instead).
Additionally, subclassing ties you to implementation details (of your parent) more than implementing an interface does. I'd say that in general it's better merely to implement the interface, at least initially, and only form class hierarchies of classes in the same or similar packages with a clear hierarchical structure.
Like you said. the implement java keyword is used to implement an interface where the extends is used to extend a class.
It depends what you would like to do. Typically you would use an interface when you want to force implementation (like a contract). Similar to an abstract class (but with an abstract class you can have non-abstract methods).
Remember in java you can only extend one class and implement zero to many interfaces for the implementing class. Unlike C# where you can extend multiple classes using :, and where C# only uses the : symbol for both interfaces and classes.
extends keyword is used for either extending a concrete/abstract class. By extending, u can either override methods of parent class / inherit them. A class can only extend class.
U can also say interface1 extends intenface2.
implements keyword is used for implementing interface. In this case u have to define all the methods indicated in interface. A class can only implement interface.

Categories