unable to understand the working of interface in java [duplicate] - java

This question already has answers here:
Java - Method name collision in interface implementation
(7 answers)
Closed 8 years ago.
I have declared an interface
public interface A {
public void print();
}
another interface
public interface B extends A {
public void print();
}
Then class
public class C implements A,B {
#Override
public void print() {
System.out.println(B.i);
}
}
Kindly tell me why there is no compile time error when both the interfaces have methods with same name and how does compiler determine which interface's method is being implemented??
thanks in advance

Implementing an interface in Java means, guaranteeing that methods, that are declared in the interface are implemented into the class.
In your example this means, that every class that implements interface A has a print-function, that takes no arguments and returns a void. Same goes for interface B. Every class that implements B has a print-funtction that take s no argument and returns a void.
If now class C implements both interfaces A and B, this means, that your class has to implement all methods that were declared in A and all methods that were declared in B. In your example these methods overlap, but do not conflict. Therefore there is no problem in that.

Your method implements both interface methods at once.

Interface B override interface A method..
When you use Interface you say to Java: "I will implement this thing"
Once the B override A you say to Java: "I will implement the same thing also on B";
So if you are implementing this once.. Basically it is like you implemented The method for both of them.. And this is not the right way to use this

Related

Rules for Diamond prob resolution or Multiple Inheritance in Java8

In Java a class can extend only one parent class but can implement multiple interfaces.
With
the introduction of default methods in Java 8 interface, there’s the possibility of a class inheriting more than one
method with the same signature by implementing 2 interfaces having the same default method
This can create diamond problem as in C++
Example in below code the output of
new C().hello(); is
This is Second
public interface First {
default void hello(){
System.out.println("This is First");
}
}
public interface Second extends First {
default void hello(){
System.out.println("This is Second");
}
}
public class MyClass implements First,Second {
public static void main(String[] args) {
new MyClass().hello();
}
}
What are the resolution rules that Java uses to resolve Diamond Problem?
A simple answer like who takes precedence and when will be great.
Following are the rules to follow when a class inherits a method with the same signature from multiple places (another class or interface):
Classes always win. A method declaration in the class or a superclass
takes priority over any default method declaration.
Otherwise, sub-interfaces win: the method with the same signature in the most specific defaultproviding
interface is selected. (for example in your case method from Second interface should run as Second extends First).
Finally, if the choice is still ambiguous, the class inheriting from multiple interfaces has to
explicitly select which default method implementation to use by overriding it and calling the
desired method explicitly.
There is the Oracle Tutorial that explains this pretty much in detail.
You have basically overridden your method from First interface and the most specific interface method is chosen.
Your snippet is no diamond problem as interface second extends interface first and overrides the method hello.
Without extending interface second the compiler throws an error
Duplicate default methods named hello with the parameters () and () are inherited from the types Second and First
Implementing two Interfaces that declare the same default Method leads to an compilation error:
MyClass inherits unrelated defaults for sayHi() from types InterfaceA and InterfaceB
So there's no Diamond-Problem ;)
To solve this you can override the Method in the implementing Class and either implement it there or defer to the correct Interface.
In your case it would look like that (in case you want to use the method of Interface First):
public class MyClass implements First,Second {
public void hello() {
First.super.hello();
}
}

Why don't implement all method in interface Comparator?

Today, I'm trying to learn some features in Java 8, specific about Lambda Expressions. I create a new Comaparator like this :
Comparator<String> strCom = new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return 0;
}
};
When I read code inside Comparator interface, I have got confused. Althrough interface Comparator have two method compare() and equals(), we don't need implement all of them. I had found some reason why we don't need implement method equals() here. But i also read in javadocs
If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile. What Is an Interface?
So, can someone help me understand this ? Do not override equals() is still legal ?
equal is not needed to implement because it is inherited from the Object class, as everything in Java is an Object
As you can see in the documentation the equal Method is already defined in the Object class:
https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html
You only need to implement the equals method if you want to check if two Comparators have the same data and therefore are "equal", but this is probably not what are you looking for, as Comparators normally do not hold any instance variables
The tutorial is trying to introduce the concept of interfaces through a simple example, but it ends up being misleading.
Take this code for example:
public interface MyInterface {
public void foo();
public void bar();
}
public class Super {
public void foo() { System.out.println("foo"); }
}
public class Sub extends Super implements MyInterface {
public void bar() { System.out.println("bar"); }
}
This is perfectly valid code, despite the fact that Sub only explicitly implements one of MyInterfaces methods. It's easy to see why this is valid: foo() is already implemented by Super, and that implementation is inherited by Sub.
The exact rule goes like this:
Unless the class being declared is abstract, all the abstract member
methods of each direct superinterface must be implemented (§8.4.8.1)
either by a declaration in this class or by an existing method
declaration inherited from the direct superclass or a direct
superinterface, because a class that is not abstract is not permitted
to have abstract methods (§8.1.1.1).
While the rule only talks about direct superclasses, it is technically also true for indirect superclasses, as method inheritance bubbles down through the hierarchy.
Given that equals() is implemented by Object and Object is the direct or indirect superclass of every class, you don't have to provide an implementation for equals().

Block an interface to be extended [duplicate]

This question already has answers here:
Final interface in Java?
(10 answers)
Closed 6 years ago.
As since in a class I can do:
public final class Foo{}
wich means no more classes can extends that Foo class... e.g. String class is final, so no custom class can extends the class String.
How can I prevent to do the same with an interface?
If I do
public interface ISome{
void fly();
}
I would like to allow that
class A implements ISome {}
but block that
public interface IHouse extends ISome{
void fly();
}
doing this
public final interface ISome{}
makes no sense... and will bring a compile error like:
Illegal modifier for the interface
You can't.
Supposedly the Java designers didn't think there would ever be an appropriate use case for this: if you don't want an interface to be extended then really you ought to declare those functions directly in a concrete class.
That said, you can achieve this in C++ as in this language an interface is more of a convention - consisting of only pure virtual functions, and you can enforce non-extensibility with techniques such as friendship.

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.

Is it possible to have an interface without a method in java

I am new to java and trying to understand interface.Making an interface without a method gives compile time error.What is the reason for this behaviour?
import java.io.*;
interface A{
int x=10;
}
class B implements A{
System.out.print("i am in B and x is"+x);
}
class InterfaceEx{
public static void main(String[] args) {
A a;
a=new B();
}
}
Yes, it's possible to have an interface without a method in Java. In fact, the Serializable and Cloneable interfaces are built-in to Java and don't have any methods. They are called "marker" interfaces.
Quoting from the Wikipedia page on marker interfaces:
Whereas a typical interface specifies functionality (in the form of
method declarations) that an implementing class must support, a marker
interface need not do so. The mere presence of such an interface
indicates specific behavior on the part of the implementing class.
As for why your B interface doesn't compile (now that you've supplied the code), you need to place your statement inside a method or constructor, such as:
class B implements A{
public B() {
System.out.print("I am in B and x is"+x);
}
}
Yes. java.io.Serializable interface is the example of such marker interface
According to the java Language Specification
The body of an interface may declare members of the interface, that
is, fields (§9.3), methods (§9.4), classes (§9.5), and interfaces
(§9.5).
It does not say you have to so yes you can have empty interfaces
And from the above answer there are empty interfaces
class B implements A{
System.out.print("i am in B and x is"+x);
}
This is not legal syntax. A class definition can only have variables or methods; that's it. That code out there by itself isn't a definition of a variable or a method, so the compiler doesn't know what to make of it.
If you define a method, then that method can have any instructions inside it.
class B implements A{
public void myMethod(){
System.out.print("i am in B and x is"+x);
}
}
You don't seem to understand what a class is, its a pretty fundamental concept to OOP and Java, although can be confusing at first.
Also, pay attention to your errors. One error is very different from another. You assumed that this error was due to an empty interface; that was wrong. It was a syntax error. If you'd read the compiler output, it would have told you this already. It tries to help you.
Interface without method are known as Marker interface.
Marker interface is used as a tag to inform a message to the java compiler so that it can add special behavior to the class implementing it.
Example: java.io.Serializable, Cloneable

Categories