Abstraction can be achieved in Java using abstract classes and interfaces.
Abstract classes
- An abstract class is a class that cannot be instantiated directly. It must be subclassed and the subclass must implement all of the abstract methods of the abstract class.
- An abstract class can have both abstract and non-abstract methods.
- An abstract class can have variables and constants.
- An abstract class can have constructors.
Example:
javapublic abstract class Animal { public abstract void makeSound(); }
Interfaces
- An interface is a reference type that defines a set of methods that must be implemented by classes that implement the interface.
- An interface cannot have any abstract methods. All of the methods in an interface are abstract by default.
- An interface cannot have any variables or constants.
- An interface cannot have constructors.
Example:
javapublic interface Flyable { void fly(); }
Real-time use-cases in Java
- Abstract class: Abstract classes are often used to implement inheritance. For example, the
java.lang.Object
abstract class is used to implement inheritance for all other classes in Java. - Interface: Interfaces are often used to implement polymorphism. For example, the
java.io.Serializable
interface is used to implement polymorphism for classes that can be serialized and deserialized.
Here is an example of a class that inherits from the
Animal
abstract class and implements the Flyable
interface:Example:
javapublic class Bird extends Animal implements Flyable { public void makeSound() { System.out.println("Chirp!"); } public void fly() { System.out.println("Flap flap!"); } }
This class implements both the makeSound()
method and the fly()
method. It can therefore be used to create objects that can both make a sound and fly.
Abstract classes and interfaces are two powerful tools that can be used to improve the design of your Java code. By using abstract classes and interfaces, you can make your code more reusable, flexible, and maintainable.
Comments
Post a Comment