Step 18:Interface – 12th hour + code

Definition-

Interface is a 100% abstract class.
– All methods in interface are public and abstract.
-All data members in interface are public, static and final.

– multiple inheritance is allowed in interfaces.

Note 1- class ‘implements’ interface

Note 2- interface ‘extends’ interface

Code samples are here

1- One class can implements multiple interfaces

multpl
a-

package intrfc;

public interface X {
void show();
}

b-

package intrfc;

public interface Y {
void display();
}

c-

package intrfc;

public class Z implements X,Y {
@Override
public void display() {
System.out.println("bye");
}

@Override
public void show() {
System.out.println("hi");
}
public static void main(String[] args) {
Z z=new Z();
z.show();
z.display();
}
}

 

2- Interface can extend other interface

a-


package intrfc;

public interface X1 {
void show();
}

b-


package intrfc;

public interface Y1 extends X1 {
void display();
}

c-


package intrfc;

public class Z1 implements Y1 {
@Override
public void display() {
System.out.println("bye");
}
@Override
public void show() {
System.out.println("hi");
}
public static void main(String[] args) {
Z1 z=new Z1();
z.show();
z.display();
}
}

 

After Java 7 – 
1- Interface’s default methods – 

public interface Person{
default String getName(){
return “kuldeep kaushik”;
}
}

Rules of interface’s default methods-

  1. If the class already has the same method as an Interface, then the default method from the implemented Interface does not take effect.
  2. If one interface inherits another interface and both of them implement a default method, the default method of the child interface would be used by an implementing class.
  3. An explicit call to an interface default method can be made from inside an implementing class using super. For example Interface.super.defaultMethod()

1- Interface’s static methods – 

public interface Test{
static String getStaticNumber(){
return 1;
}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.