Feature | Abstract Class | Interface |
---|---|---|
Definition | A class that can have both abstract methods (without a body) and concrete methods (with a body). | A blueprint that only contains abstract methods (until Java 8, after which default and static methods were introduced). |
Usage | Used to represent a base class that provides partial implementation for subclasses. | Used to define a contract that implementing classes must adhere to. |
Inheritance | A class can extend only one abstract class (single inheritance). | A class can implement multiple interfaces (multiple inheritance). |
Access Modifiers | Abstract classes can have any access modifier for methods and fields (e.g., private, protected, public). | All methods in an interface are public by default. |
Fields | Can have instance variables and static variables. | Fields are implicitly public, static, and final (constants). |
Constructor | Can have a constructor to initialize fields. | Cannot have a constructor. |
Example |
|
|
Answer:
Java implements multiple inheritance through interfaces.
A class can implement multiple interfaces, thus inheriting behavior from all of them.
This avoids the "diamond problem" caused by ambiguity in multiple inheritance.
interface InterfaceA {
void methodA();
}
interface InterfaceB {
void methodB();
}
class MultiInheritanceClass implements InterfaceA, InterfaceB {
public void methodA() {
System.out.println("Method A from InterfaceA");
}
public void methodB() {
System.out.println("Method B from InterfaceB");
}
}
public class Test {
public static void main(String[] args) {
MultiInheritanceClass obj = new MultiInheritanceClass();
obj.methodA();
obj.methodB();
}
}
Answer: No, a class cannot be both abstract
and final
because an abstract class is meant to be extended, whereas a final class cannot be extended.
Answer: A constructor is a special method used to initialize objects. Types:
Answer: The super
keyword is used to refer to the immediate parent class. It can be used to call the parent class constructor or methods.
class Animal {
void eat() {
System.out.println("Animal eats.");
}
}
class Dog extends Animal {
void eat() {
super.eat();
System.out.println("Dog eats.");
}
}
Method Overloading: This occurs when multiple methods in the same class share the same name but have different parameter lists (number, type, or order of parameters). It is a compile-time polymorphism.
Key Points:
class Calculator {
// Overloaded methods
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
public class OverloadingExample {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(2, 3)); // Calls int add(int, int)
System.out.println(calc.add(2.5, 3.5)); // Calls double add(double, double)
System.out.println(calc.add(1, 2, 3)); // Calls int add(int, int, int)
}
}
Method Overriding: This occurs when a subclass provides a specific implementation for a method already defined in its parent class. It is runtime polymorphism.
Key Points:
@Override
annotation is used for clarity and to catch errors.
class Parent {
void display() {
System.out.println("Display from Parent");
}
}
class Child extends Parent {
@Override
void display() {
System.out.println("Display from Child");
}
}
public class OverridingExample {
public static void main(String[] args) {
Parent obj = new Child(); // Upcasting
obj.display(); // Calls Child's overridden method
}
}
Tricky Points:
No, static methods cannot be overridden in Java. Instead, if a static method is defined in both the parent and child classes with the same name and parameters, it is known as method hiding. The method called depends on the reference type, not the object type.
class Parent {
static void staticMethod() {
System.out.println("Static method in Parent");
}
}
class Child extends Parent {
static void staticMethod() {
System.out.println("Static method in Child");
}
}
public class StaticMethodTest {
public static void main(String[] args) {
Parent parent = new Parent();
Parent childAsParent = new Child();
Child child = new Child();
parent.staticMethod(); // Outputs: Static method in Parent
childAsParent.staticMethod(); // Outputs: Static method in Parent (method hiding)
child.staticMethod(); // Outputs: Static method in Child
}
}
Key Points:
Answer: An inner class in Java is a class that is defined within another class. Inner classes are used to logically group classes that are only used in one place, improve encapsulation, and make the code more readable and maintainable.
Types of Inner Classes:
Example: Member Inner Class
class OuterClass {
private String message = "Hello from Outer Class!";
class InnerClass {
void displayMessage() {
System.out.println(message); // Accessing private member of the outer class
}
}
}
public class InnerClassExample {
public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.displayMessage();
}
}
Why Use Inner Classes?
Answer:
this
: Refers to the current object.super
: Refers to the parent class object.Answer: Create a class with:
final class Immutable {
private final String name;
Immutable(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Answer: A sealed class in Java restricts the inheritance of the class to a specific set of classes. It is a way to restrict the subclassing of a class, ensuring that only a designated set of classes can inherit it. Sealed classes are introduced in Java 16.
Key Features:
Example:
sealed class Shape permits Circle, Rectangle {
double area;
Shape(double area) {
this.area = area;
}
abstract double calculateArea();
}
final class Circle extends Shape {
Circle(double area) {
super(area);
}
@Override
double calculateArea() {
return Math.PI * area * area;
}
}
final class Rectangle extends Shape {
double length, width;
Rectangle(double area, double length, double width) {
super(area);
this.length = length;
this.width = width;
}
@Override
double calculateArea() {
return length * width;
}
}
public class SealedClassExample {
public static void main(String[] args) {
Shape circle = new Circle(10.0);
Shape rectangle = new Rectangle(20.0, 5.0, 4.0);
System.out.println("Circle Area: " + circle.calculateArea());
System.out.println("Rectangle Area: " + rectangle.calculateArea());
}
}
Why Use Sealed Classes?
Answer: It states that objects of a superclass should be replaceable with objects of its subclasses without affecting the functionality of the program.
Answer: Yes, an interface can extend another interface. This allows a child interface to inherit methods from the parent interface.
Answer: The instanceof
keyword is used to test whether an object is an instance of a specific class or subclass.
Answer: Default methods, introduced in Java 8, allow adding new methods to interfaces without breaking existing implementations.
Answer: A functional interface is an interface with a single abstract method. It is used in lambda expressions and method references. Example: Runnable
, Predicate
.
Answer: Java provides cloning using the clone()
method of the Object
class. A class must implement Cloneable
to use it.
Answer: Composition is a design principle where a class contains objects of other classes to achieve reusability.
Answer: Dependency Injection is a design pattern where objects are provided their dependencies instead of creating them internally, promoting loose coupling.
Answer: A default constructor is provided by Java if no constructor is explicitly defined. It initializes objects with default values.
Answer: Method hiding occurs when a static method in a subclass has the same name and signature as one in its superclass. The method is hidden, not overridden.
Answer: SOLID principles are design principles for maintainable software:
Answer:
Answer: This principle states that a class should be open for extension but closed for modification.
Answer: A class should only have one reason to change. You can achieve this by keeping related functionalities together and separating unrelated functionalities into different classes.