Java Tutorial
.
Java programming's abstract class and interface concepts are two key ideas that are essential for attaining abstraction and putting inheritance into practice. By declaring abstract methods that we expect will be defined in the implementing class, for instance, abstract classes can express the same set of assertions as interfaces can.
Even though they are similar, they also have unique qualities that make them stand out. In this post, we'll examine the distinctions between abstract classes and interfaces, as well as each one's characteristics and appropriate Java usage.
Before diving into the specifics, let's start with a brief overview of interfaces and abstract classes. An interface in Java is a blueprint of a class that defines a set of methods that implementing classes must adhere to. It acts as a contract, ensuring that any class implementing the interface must implement all of its methods. Interfaces cannot be instantiated directly and are declared using the interface keyword.
On the other hand, an abstract class in Java is a class that cannot be instantiated directly but can be subclassed. It serves as a blueprint for derived classes and can contain both abstract and non-abstract methods. Both abstract classes and interfaces are used to define abstract methods, which are methods without any implementation. They provide a way to enforce certain behaviors in classes that inherit from them. However, there are differences in how they are defined and utilized in Java.
In Java, a class's interface is a blueprint that specifies a set of methods that implementing classes must follow. It serves as a contract, requiring that every class that implements the interface also implement every one of its methods. The interface keyword is used to declare an interface, which may include method signatures, constant variables, and default methods.
Here’s an example:
abstract class sunstar { abstract void printInfo(); } class employee extends sunstar { void printInfo() { String name = "avinash"; int age = 21; float salary = 222.2F; System.out.println(name); System.out.println(age); System.out.println(salary); } } class base { public static void main(String args[]) { sunstar s = new employee(); s.printInfo(); } }
Output: avinash 21 222.2
Properties of an Interface
They cannot be instantiated directly: An interface cannot be instantiated directly using the new keyword. It serves as a blueprint for implementing classes.
They are implemented by classes: Interfaces are implemented by classes using the implements keyword. A class can implement multiple interfaces, providing the implementation for all the methods declared in those interfaces.
They contain only abstract methods: By default, all methods declared in an interface are abstract and do not have an implementation. They only specify the method signature. Implementing classes must provide the implementation for these methods.
They support multiple inheritance: Unlike classes, which can only extend a single superclass, interfaces support multiple inheritance. A class can implement multiple interfaces, inheriting and implementing the methods defined in each interface.
public class Dog implements Animal { @Override public void eat() { // Implementation for eat() specific to Dog } @Override public void sleep() { // Implementation for sleep() specific to Dog } }
In this example, the Dog class provides its own implementation for the eat() and sleep() methods defined in the Animal interface. The user of the Dog class does not need to know the implementation details of these methods. They can interact with the Dog object through the Animal interface, which provides a high level of abstraction.
They have constant variables: Interfaces can also contain constant variables, which are by default public, static, and final. These variables can be accessed using the interface name followed by the variable name.
Default methods: Starting from Java 8, interfaces can have default methods. A default method is a method with a default implementation provided within the interface itself. Default methods allow interfaces to provide a default behavior that implementing classes can optionally use or override.
Abstraction is a fundamental concept in computer science and software engineering that involves simplifying complex systems by focusing on essential features and hiding unnecessary details. It allows us to create models that capture the essential characteristics of real-world objects or systems, without getting into the specifics of how those objects or systems are implemented.
In the context of programming, abstraction helps in designing and implementing software systems by providing a high-level view and separating the concerns of different components. It allows programmers to create classes, interfaces, and methods that represent real-world entities or concepts, while abstracting away the complexities of their internal workings.
They cannot be instantiated: Abstract classes cannot be directly instantiated using the new keyword. They serve as blueprints for creating concrete subclasses. Example:
// Java Program to Illustrate // that an instance of Abstract // Class can not be created // Class 1 // Abstract class abstract class Base { abstract void fun(); } // Class 2 class Derived extends Base { void fun() { System.out.println("Derived fun() called"); } } // Class 3 // Main class class Main { // Main driver method public static void main(String args[]) { // Uncommenting the following line will cause // compiler error as the line tries to create an // instance of abstract class. Base b = new Base(); // We can have references of Base type. Base b = new Derived(); b.fun(); } }
Output:
Derived fun() called
In the given code, the derived class (Derived) is calling the abstract base class (Base) internally through inheritance and polymorphism. The Derived class extends the Base abstract class and overrides the abstract method fun().
In the Main class, an object of the Derived class is created and assigned to a reference variable of the Base type. Through polymorphism, the overridden fun() method in the Derived class is called using the reference variable of the abstract class type. This allows the code to execute the implementation defined in the Derived class.
They can have both abstract and non-abstract methods: Abstract classes can contain both abstract and non-abstract methods. Abstract methods are declared without an implementation, while non-abstract methods have a defined implementation. Subclasses of an abstract class must provide implementations for all abstract methods.
They can have instance variables: Abstract classes can have instance variables, constructors, and other features similar to regular classes. Subclasses can inherit these variables and methods.
They can also provide default behavior: Abstract classes can provide default implementations for certain methods. Subclasses have the option to override these methods or use the default implementation.
What is an Abstract Class in Java?
An abstract class in Java is a class that cannot be instantiated directly but can be subclassed. It can contain both abstract and non-abstract methods, just like a regular class. However, abstract methods in an abstract class do not have an implementation.
Here’s an example:
// Abstract Class abstract class sunstar { abstract void printInfo(); } class employee extends sunstar { void printInfo() { String name = "avinash"; int age = 21; float salary = 222.2F; System.out.println(name); System.out.println(age); System.out.println(salary); } } class base { public static void main(String args[]) { sunstar s = new employee(); s.printInfo(); } }
Output: avinash 21 222.2
This code demonstrates the usage of an abstract class (sunstar) and its subclass (employee). The employee class extends the Sunstar abstract class and overrides the printInfo() method. In the main method, an object of the employee class is created and assigned to a reference variable of the sunstar type.
Through polymorphism, the overridden printInfo() method in the employee class is called using the reference variable of the abstract class type, resulting in the output of employee information.
Let's compare abstract classes and interfaces based on various parameters:
Parameter | Abstract Class | Interface |
Instantiation | Cannot be instantiated directly | Cannot be instantiated directly |
Inheritance | Can be extended by subclasses | Can be implemented by classes |
Method Implementation | Can contain both abstract and non-abstract methods | Contains only abstract methods by default |
Multiple Inheritance | Does not support multiple inheritance | Supports multiple inheritance via interfaces |
Accessibility of Variables | Can have instance variables with various access modifiers | Only supports public static final variables |
Default Implementation | Can provide default implementation for methods | Introduced in Java 8 using default methods |
Extending Other Classes | Can extend only one class | Can extend multiple interfaces |
Purpose | Used when there is a "is-a" relationship | Used when there is a "can-do" relationship |
Let's take a closer look at the features of abstract classes and interfaces.
They allow for partial implementation: Abstract classes can provide both abstract methods (methods without implementation) and concrete methods (methods with implementation). This allows abstract classes to provide a partial implementation of functionality that can be inherited by subclasses.
They can have constructors: Abstract classes can have constructors that are invoked when an object of a concrete subclass is created. Constructors in abstract classes are used to initialize the state of the abstract class and can be invoked using the super() keyword from the subclass.
They can have instance variables: Abstract classes can have instance variables that are inherited by subclasses. Subclasses can access and use these instance variables.
Here's an example of an abstract class with an instance variable:
abstract class Shape { protected String color; public Shape(String color) { this.color = color; } abstract void draw(); }
In the above example, the Shape abstract class has an instance variable color that is accessible to its subclasses.
Interfaces in Java have the following features:
Method signatures: Interfaces define method signatures without any implementation. They specify the method name, parameters, and return type, but leave the implementation details to the classes that implement the interface.
Multiple inheritance: Unlike classes, a Java class can implement multiple interfaces. This allows a class to inherit and provide implementation for multiple sets of behaviors defined by different interfaces.
No instance variables: Interfaces cannot have instance variables. They can only have constants (public, static, and final variables) and method declarations.
Default methods: Starting from Java 8, interfaces can have default methods. A default method provides a default implementation that can be used by implementing classes. This allows interfaces to evolve and add new methods without breaking the existing code.
Static methods: Starting from Java 8, interfaces can also have static methods. Static methods in interfaces provide utility methods that are not tied to any specific implementation and can be directly invoked using the interface name.
Used for type abstraction: Interfaces are primarily used for achieving type abstraction in Java. By implementing an interface, a class defines that it can exhibit a certain behavior or fulfill a contract defined by the interface.
Use an interface in the following scenarios:
When you want to provide a common behavior that can be implemented by multiple classes.
When you want to achieve multiple inheritances for classes.
When you want to define a contract that classes must adhere to.
Use an abstract class in the following scenarios:
When you want to define a common base for a group of related classes
When you want to provide a default implementation for some methods that can be overridden by subclasses
When you want to enforce certain methods to be implemented by subclasses
Use Interface in Java in the following scenarios:
When you want to create a contract for classes to follow
When you want to achieve full abstraction
When you want to support multiple inheritance
Abstract classes are used to define common behavior and provide a base for subclasses, while interfaces define a contract that classes must adhere to. By understanding the differences and characteristics of abstract classes and interfaces, you can make informed decisions on when to use each of them in your Java projects. Mastering these concepts will help you build more modular, maintainable, and flexible code.
1. What unique features does an interface bring to Java programming, especially when contrasted with the difference between a class and an abstract class in Java?
Interfaces in Java offer full abstraction and enable multiple inheritance. Unlike classes or abstract classes, they only contain method signatures without implementation, ensuring a defined contract for classes to follow.
2. What is the difference between a class and an abstract class in Java?
A class in Java is a blueprint from which individual objects are created, and can fully implement methods. In contrast, an abstract class, while also a blueprint, cannot be instantiated and often contains one or more abstract methods that are declared but not implemented, requiring subclasses to provide the implementation.
3. What are the rules to be followed for abstract classes?
Abstract classes cannot be instantiated directly; they can only be used as a base for subclasses
Abstract classes can have both abstract and non-abstract methods
Leave a Reply
Your email address will not be published. Required fields are marked *