Introduction
Interfaces help different parts of a program work together by agreeing on what methods to use. They let us write flexible and organized code.
Jump into concepts and practice - no test required
Interfaces help different parts of a program work together by agreeing on what methods to use. They let us write flexible and organized code.
public interface InterfaceName { void method1(); int method2(String param); }
public interface Animal { void sound(); }
public class Dog implements Animal { public void sound() { System.out.println("Bark"); } }
public class Cat implements Animal { public void sound() { System.out.println("Meow"); } }
This program shows how two different vehicles use the same interface to start and stop, but each has its own way.
public interface Vehicle { void start(); void stop(); } public class Car implements Vehicle { public void start() { System.out.println("Car is starting"); } public void stop() { System.out.println("Car is stopping"); } } public class Bike implements Vehicle { public void start() { System.out.println("Bike is starting"); } public void stop() { System.out.println("Bike is stopping"); } } public class Main { public static void main(String[] args) { Vehicle myCar = new Car(); Vehicle myBike = new Bike(); myCar.start(); myBike.start(); myCar.stop(); myBike.stop(); } }
Interfaces help make your code easier to change and add new features without breaking old code.
One class can use many interfaces, which helps organize different abilities.
Interfaces are like contracts that say what a class must do, but not how.
Interfaces define a set of methods that classes must implement.
They help different classes work together by sharing common method names.
Using interfaces makes your code flexible and easier to maintain.
interface defines methods but no implementation. What is the main reason to use them?interface followed by name and method signatures without bodies.void move(); is correct.interface Animal { void sound(); }
class Dog implements Animal {
public void sound() { System.out.println("Bark"); }
}
public class Test {
public static void main(String[] args) {
Animal a = new Dog();
a.sound();
}
}sound() method printing "Bark".a is Animal type but refers to Dog object, so a.sound() calls Dog's method printing "Bark".interface Shape {
void draw();
}
class Circle implements Shape {
void draw() { System.out.println("Circle drawn"); }
}draw() in Circle has default (package-private) visibility, missing public.connect() to work with the computer.connect(), letting each class implement it as needed.