Java
Java
class Geeks
{...}
Output
Geek
10
Note: In Java, the abstract keyword applies only to classes and
methods, indicating that they cannot be instantiated directly and must be
implemented. When we decide on a type of entity by its behaviour and
not via attribute we should define it as an interface.
Syntax
interface {
// declare constant fields
// declare methods that abstract
// by default.
}
To declare an interface, use the interface keyword. It is used to provide
total abstraction. That means all the methods in an interface are declared
with an empty body and are public and all fields are public, static, and
final by default. A class that implements an interface must implement all
the methods declared in the interface. To implement the interface, use
the implements keyword.
Relationship Between Class and Interface
A class can extend another class, and similarly, an interface can extend
another interface. However, only a class can implement an interface, and
the reverse (an interface implementing a class) is not allowed.
Difference Between Class and Interface
Although Class and Interface seem the same there are certain differences
between Classes and Interface. The major differences between a class
and an interface are mentioned below:
Class Interface
A class can contain concrete (with The interface cannot contain concrete (with
implementation) methods implementation) methods.
The access specifiers used with classes are In Interface only one specifier is used-
private, protected, and public. Public.
Implementation: To implement an interface, we use the keyword
implements
Let’s consider the example of Vehicles like bicycles, cars, and bikes share
common functionalities, which can be defined in an interface, allowing
each class (e.g., Bicycle, Car, Bike) to implement them in its own way.
This approach ensures code reusability, scalability, and consistency
across different vehicle types.
Example:
import java.io.*;
interface Vehicle {
int speed;
int gear;
// Change gear
@Override
public void changeGear(int newGear){
gear = newGear;
}
// Increase speed
@Override
public void speedUp(int increment){
speed = speed + increment;
}
// Decrease speed
@Override
public void applyBrakes(int decrement){
speed = speed - decrement;
}
int speed;
int gear;
// Change gear
@Override
public void changeGear(int newGear){
gear = newGear;
}
// Increase speed
@Override
public void speedUp(int increment){
speed = speed + increment;
}
// Decrease speed
@Override
public void applyBrakes(int decrement){
speed = speed - decrement;
}