Java - implements Keyword
Generally, the Java implements keyword is used with classes to inherit the properties of an interface. Interfaces can never be extended by a class.
Example
interface Animal {
}
class Mammal implements Animal {
}
public class Dog extends Mammal {
}
Sample Code
This section provides you a program that demonstrates the usage of the implements keyword.
In the given program, you have two classes namely Mammal and Dog. Mammal class is implementing an interface Animal.
Copy and paste the program in a file with name Dog.java.
Example
interface Animal {
}
class Mammal implements Animal {
}
public class Dog extends Mammal {
public static void main(String args[]) {
Mammal m = new Mammal();
Dog d = new Dog();
System.out.println(m instanceof Animal);
System.out.println(d instanceof Mammal);
}
}
Output
On executing the program, you will get the following result −
true true
Following is another example, where we can use implements keyword to implement multiple interfaces in single class.
Example
interface Animal {
}
interface CanMove {
}
class Mammal implements CanMove, Animal {
}
public class Dog extends Mammal {
public static void main(String args[]) {
Mammal m = new Mammal();
Dog d = new Dog();
System.out.println(m instanceof Animal);
System.out.println(m instanceof CanMove);
System.out.println(d instanceof Mammal);
}
}
Output
On executing the program, you will get the following result −
true true true
java_basic_syntax.htm
Advertisements