Interface Method Usage(Java)? - java

Can Someone Explain how the methods of interface used in classes?
Note: My Doubt is "Methods are already defined in Class then why we should implement it ? "
For Example :
interface printable{
void print();
}
class A implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A obj = new A();
obj.print();
}
}
why print() is declared in interface??

You define a method by giving its implementation. They are the same thing, so you are right that once you define a method, you don't also need to implement it.
An interface declares that anything implementing this interface will defined those methods. This is part of the contract for interfaces. This allows you to call any method of an interface knowing than any concrete implementation will have such a method.
BTW In Java 8, it will support virtual extensions which means an interface can give a default implementation. This has to be defined in terms of other methods provided by the interface.

An Interface is a contract that all classes that implement it, should have a definition for the methods specified in the interface. An interface does not define the method body as such.

An interface defines a set of method which must be implemented. It says nothing on how they are implemented. This is where the class definition comes in, since it defines how these methods are implemented.
Thus, when you call a class which implements a particular interface, then you know, for sure, that you will find whatever set of methods the interface defines.
Interfaces are usually handy when you need to expose some endpoints to your application, without the need to expose the logic.
EDIT: As per your example, the printable interface defines what behaviour should a class which implements it expose, in this case print.
This will allow you to do something along the lines of printable p = new A(); p.print();.
Assuming you have something which yields an object which implements the printable interface, then, whoever is calling that method will not need to bother what is the actual implementation of the print method. The interface makes sure that whatever you are returning, will contain an implementation of that method.

#NarutoUzumaki
Welcome to Stack overflow!
I agree with Chris. You can replace the doSomething method with eat() method to get a better understanding. A dog may eat something different than a cat and to a giraffe.
Its up to you how you implement the eat method, and when using it create a reference of the interface Animal and point it to the instance of Dog, Cat or Giraffe which ever eat method you want to use. This makes your class design very extensible.
Hope you get a clear idea now.

Generally Interface based Programming is recommended, Because of the following reasons
1)Interface means rule , you should follow those rules while implementing those methods in Implemented class.
2) Dependency is less between classes while instancing your implemented class then call your methods from another class or some where.
3) You can publish your interface details only no need to disclose the implemented details of your methods to out side the world.

Defining an interface is the difference between:
public void doSomething(Dog d)
{
d.doSomething();
}
public void doSomething(Cat c)
{
c.doSomething();
}
public void doSomething(Giraffe g)
{
g.doSomething();
}
and
public void doSomething(Animal a)
{
a.doSomething();
}
Why?
Well, if all the classes just implement their own methods, there's no common reference between them. However, if they all implement the method from a common interface, they can be referred to by the same reference type; in this case Animal.

Related

How the compiler will get to know which print method should be called by obj.print();?

Here is an example of interface which is showing multiple inheritance.And i want to know how can we achieve multiple inheritance by interface and why can't we use it by class?
interface Printable // interface1
{
void print();
}
interface Showable //interface2
{
void print();
}
class TestTnterface1 implements Printable,Showable
{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
TestTnterface1 obj = new TestTnterface1();
obj.print(); //which print method will be called now?
}
}
First question:
The implementation satisfies both contracts, so whether you cast your concrete class to Printable or Showable, it will be used just the same. You will notice that there is an "impossible" situation, like this:
public interface Printable{
String print();
}
public interface Showable{
void print();
}
public class Impl implements Printable,Showable{
/*impossible to implement because you cannot have the same method signature with two different return types*/
}
The multiple inheritance would usually imply there is something useful added by each parent. For example, if Printable would have the method #print and Showable would have the method #show, inheriting them both would add functionality to your program.
If you want to combine functionality from several concrete classes, you might want to look into composition instead of inheritance.
The answer to the second question is more tricky. You can find a longer discussion here. While it would have been possible for the creators of Java to put in such option, it would have opened the door to some pretty messed up code. Think of the example you gave: what if Printable and Showable had concrete implementations for the #print method? Which implementation should the inheriting class have chosen?
In any case the runtime will call the TestTnterface1#print() method, because it is the implementation (code that can be executed).
An interface is a contract that the class that implements must follow, and is used only at compile time. The compiler checks, if the implementor has (non abstract) methods with same name and signature.
There is only one concrete method that can be called
i.e.
class TestTnterface1 implements Printable,Showable
{
public void print()
{
System.out.println("Hello");
}
Question 1: Which method is called?
There is only one method-implementation that can actually be called. So, there is no ambiguity.
Question 2: How can we achieve multiple inheritance by interface?
You already gave an example for this. The special point about this kind of inheritance is that there can't be multiple implementations (until Java 7). Java 8 in contrast allows default methods in interfaces.
Question 3: Why can't we use it by class?
It avoids inheritance of state.
https://docs.oracle.com/javase/tutorial/java/IandI/multipleinheritance.html gives some more information.
Since both interfaces have print() method and TestInterface1 class has its implementation, it will call its implementation.
public void print()
{
System.out.println("Hello");
}

Invoke a method on all subclasses from superclass?

I have recently stubled upon something that has always annoyed me.
Whenever I want a method to be invoked in all classes that have a certain interface, or if they are extensions, I would like to have a keyword that does the opposite of the keyword super. Basically, I want the invocation to be passed down (if a class inherits a method, and the method in the superclass is called, it will be called in the subclass as well). Is there anything that resembles what I am asking for?
EDIT:
The contemporary methods I am using are efficient, but not as efficient as I would like them to be. I am only wondering if there is a way of invoking a method, that has been inherited, from its superclass/superinterface. The last time I was looking for this, I did not find it either.
NOTE: All of the subclasses are unknown, hence impossible to utilize. The only known class is the superclass, which is why I can't invoke it. This can be solved using the Reflections API, which I am currently using. However, it does not always comply with what I am searching for.
Every method in Java is virtual with the exception of static methods, final methods and constructors meaning that if a subclass implements the method being invoked, the subclass's implementation will be called. If the subclass wishes to also invoke the immediate superclass method, that is accomplished via a call to super.
This is very common with abstract classes where some base class is utilized by a framework, but clients are expected to override. For instance:
public abstract class Drawer{
public void draw(){
//setup code, etc common to all subclass implementations
doDraw();
}
protected abstract void doDraw();
}
public class CircleDrawer extends Drawer{
protected void doDraw(){
//implementation of how to actually draw a circle
}
}
Now, when you have an instance of CircleDrawer and you call draw(), the superclass Drawer.draw() method will be invoked that is, in turn, able to call CicleDrawer.doDraw().
Edit Now, if CircleDrawer was this:
public class CircleDrawer extends Drawer{
public void draw(){
//do stuff
}
protected void doDraw(){
//implementation of how to actually draw a circle
}
}
Any invocation of Drawer.draw() on an instance of CircleDrawer will always invoke the CircleDrawer.draw() method.
If you mean something like this:
class A {
public void func1(){
//do stuff
subclass.func1();
}
}
class B extends A{
public void func1(){
//do more stuff
}
}
class C extends A{
}
What happens when I call new C().func1()? Remember, func1 is not abstract and therefore, you cannot require classes to define it.
A better solution is to do the following:
abstract class A {
public void func1(){
//do stuff
func2();
}
public abstract func2();
}
class B extends A{
public void func2(){
//do more stuff
}
}
Hence, you require your subclasses to define a function that you can call from the super class.
The is no such a thing. When calling an overriden method in Java, the child-most class's method will be always called. If you want to call parent methods as well, you need to use super.methodCall() in every class's method of your hirearchy.
Unfortunately, I don't believe the thing you are trying to do is as possible as you may think. It's not quite that easy to invoke your subclasses from the super class, because not all subclasses may behave in the same way so a generic keyword for that functionality would wreak havoc! Although, by the phrasing of "Basically, I want the invocation to be passed down." it sounds like what you want is normal inheritance.
Just define the most generic similarities that all subclasses have in common in the superclass, then simply start each subclass definition of the method with super()
I don't mean to point out the obvious, but OO was designed for that and not for what you are asking. I doubt you'll be unable to find a way to do what you want within the typical arsenal of OO concepts
I think you got confused describing what you need, I don't think this:
Whenever I want a method to be invoked in all classes that have a certain interface, or if they are extensions
Is the same as this:
I would like to have a keyword that does the opposite of the keyword super
From what I understand, in the first one, you are referring to calling a method for all instances of a base class and its subclasses. For the second one, calling a subclass' method is exactly calling that method on a subclass which has probably overriden it.
I'm not sure what you are trying to do, maybe you should clarify with an example. Most likely, yours is a design problem which is solved in a different way than the one you are proposing. However, a "solution" came to mind when reading your question.
I'm a little more experienced with C# and python than with Java (and not even that much), but I'm sure more experienced programmers won't hesitate to correct me if I said stupid things.
You should have some kind of collection of objects of type of the base class and call that method, on each object, which each subclass must have overriden.
Maybe using the observer pattern, which is commonly used to reproduce event triggering, you can make all instances of a base class and its subclasses execute a "callback" whenever you want.

What is the need to use Interface in java? [duplicate]

This question already has answers here:
what is the actual use of interface in java? [duplicate]
(6 answers)
Closed 9 years ago.
I am just in little bit confusion about for what interface used in Java.
For example, I am creating an interface like,
interface Inter
{
void get();
}
And I am implementing it in a class like,
class Base implements Inter
{
void get()
{
------
}
}
Whats the difference between, if I declare a class like
class Base
{
void get()
{
------
}
}
Is there any difference in it? then why should I use interface in java. I know its a basic question. but I am in confusion. So please solve this..
An interface makes the contract between caller and called classes more explicit.
Also, it allows you to mimic multiple inheritance to a certain extent (say you
have super class A and you cannot change it, you can still implement some
interface B and pass your class to a method which accepts B as parameter
but knows nothing about your super-class A).
public interface Animal {
public void eat();
public void sleep();
}
public class Dog implements Animal{
// Now FOR A DOG TO BE AN ANIMAL, IT MUST IMPLEMENT ALL THE BEHAVIOURS(METHODS) OF ANIMAL INTERFACE. IF IT MISSES EVEN ONE BEHAVIOUR, THEN A DOG IS NOT AN ANIMAL.
public void eat()
{
}
public void sleep()
{
}
}
Why Interfaces?
An interface is a contract or a protocol, or a common understanding of what the classes can do. When a class implements a certain interface, it promises to provide implementation to all the abstract methods declared in the interface. Interface defines a set of common behaviors. The classes implement the interface agree to these behaviors and provide their own implementation to the behaviors. This allows you to program at the interface, instead of the actual implementation.
One of the main usage of interface is provide a communication contract between two objects. If you know a class implements an interface, then you know that class contains concrete implementations of the methods declared in that interface, and you are guaranteed to be able to invoke these methods safely. In other words, two objects can communicate based on the contract defined in the interface, instead of their specific implementation.
First, it can be usefull because you can't herit from multiple class.
And then it is a kind of contract also.
All classes which implements Movable will be able to move, but each one with his own way.
So when you handle a Movable, no matter his class, you know that you can use the method move().
Hope it helps.

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

Confusion in regarding implementing interface methods

HI
I have a question If interface has got four methods,and I like to implement only two methods, how this could be achieved?
Can any explain is that possible or should I go for implementing all the methods.
You can't "partially" implement an interface without declaring the implementing class abstract, thereby requiring that some subclass provide the remaining implementation. The reason for this is that an interface is a contract, and implementing it declares "I provide the behavior specified by the interface". Some other code is going to use your class via the declared interface and will expect the methods to be there.
If you know the use case does not use the other two methods you can implement them by throwing OperationNotSupported. Whether this is valid or not very much depends on the interface and the user. If the interface can legitimately be partially implemented this way it would be a code smell that the interface is poorly designed and perhaps should have been two interfaces.
You may also be able "implement" the interface by doing nothing, though this is usually only proper for "listener" or "callback" implementations.
In short, it all depends.
If you control the design of the interface, simply split it in two. One interface specifies the two only some implementations implement, and one interface specifies the other two (or inherits the first two and adds more, your choice)
You can make the implementing class abstract and implement two of the 4 methods from the interface.
I think #sateesh 's answer is the one closer to solving your problem. Let me elaborate on it. First of all, it is imperative that any class implementing an interface should provide definitions for all of its methods. But in some cases the user may find no use for a majority of the methods in the interface save for one or two. Consider the following interface having 6 abstract methods:
public interface HugeInterface {
void a();
void b();
void c();
void d();
void e();
void f();
}
Suppose your code finds use for the method 'c()' only and you wish to provide implementation details for only the method 'c()'. You can create a new class HugeInterfaceAdapter in a separate file which implements all the methods of the interface HugeInterface like shown below:
public class HugeInterfaceAdapter implements HugeInterface {
public void a() {}
public void b() {}
public void c() {}
public void d() {}
public void e() {}
public void f() {}
}
Note that you need not provide any actual implementation code for any of the methods. Now comes the interesting part. Yes, your class in which the need to implement a huge interface arose in the first place.
public class MyClass {
HugeInterfaceAdapter mySmallInterface = new HugeInterfaceAdapter() {
#Override
public void c() {
//Your class-specific interface implementation code here.
}
};
}
Now you can use the reference variable mySmallInterface in all the places where a HugeInterface is expected. This may seem a little hackish but I may say that it is endorsed officially by Java and classes like MouseAdapter bears testimony to this fact.
It's not possible.
You can implement all four methods, but the two you don't need should throw an UnsupportedOperationException.
If you want a concrete class which is implementing this interface, then it is not possible to have unimplemented methods, but if you make have abstract class implementing this interface then you can leave any number of methods as you want to be unimplemented.
As other answers mention you cannot have a concrete class implementing only some of the methods of the interface it implements. If you have no control over the interface your class is extending, you can think of having Adapter classes.
The abstract Adapter class can provide dummy implementation for the methods of an interface and the client classes can
extend the Adapter class. (Of course the disadvantage is that you cannot extend more than one class)
This is common practice with GUI programming (using Swing) where the event listener class
might not be interested in implementing all methods specified by the EventListener interface. For example
take a look at the java.awt.event.MouseListener interface and and the corresponding adapter class java.awt.event.MouseAdapter.

Categories