interface class in java code example
Example 1: Interface in java
interface Vehicle
{
public void accelerate();
}
class BMW implements Vehicle
{
public void accelerate()
{
System.out.println("BMW accelerating...");
}
}
public class InterfaceDemo
{
public static void main(String[] args)
{
BMW obj = new BMW();
obj.accelerate();
}
}
Example 2: how to implement a interface in java
interface methods{
public static hey();
}
class scratch implements methods{
public static hey(){
System.out.println("Hey");
}
}
Example 3: interface in java
Interfaces specify what a class must do.
It is the blueprint of the class.
It is used to achieve total abstraction.
We are using implements keyword for interface.
Basic statement we all know in Selenium is
WebDriver driver = new FirefoxDriver();
WebDriver itself is an Interface.
So we are initializing Firefox browser
using Selenium WebDriver.
It means we are creating a reference variable
of the interface and creating an Object.
So WebDriver is an Interface and
FirefoxDriver is a class.
Example 4: interface in java
public class MammalInt implements Animal {
public void eat() {
System.out.println("Mammal eats");
}
public void travel() {
System.out.println("Mammal travels");
}
public int noOfLegs() {
return 0;
}
public static void main(String args[]) {
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
Example 5: Interface in java
interface InterfaceName
{
fields
methods
}
Example 6: why we use interface in java
interface Animal {
void child();
}
class Cat implements Animal {
public void child() {
System.out.println("kitten");
}
}
class Dog implements Animal {
public void child() {
System.out.println("puppy");
}
}
public class LooseCoupling{
public static void main(String args[]) {
Animal obj = new Cat();
obj.child();
}
}