Java Programming Inheritance And Method Overriding Complete Guide
Understanding the Core Concepts of Java Programming Inheritance and Method Overriding
Java Programming: Inheritance and Method Overriding
Introduction
Inheritance
Inheritance allows a new class, known as a subclass or derived class, to inherit the properties (variables) and behaviors (methods) of an existing class, referred to as a superclass or base class. This mechanism promotes code reusability and establishes a hierarchical relationship among classes.
Syntax:
class SuperClass {
// Properties and Methods
}
class SubClass extends SuperClass {
// Additional Properties and Methods
}
Key Points:
- Single Inheritance: Java supports single inheritance, meaning a class can directly extend only one superclass. Multiple inheritance is not allowed to avoid ambiguity. However, Java handles multiple inheritance through interfaces.
- Protected Members: Using the
protected
access modifier, subclasses can access superclass methods and properties within the same package or outside the package but within subclasses only, ensuring encapsulation. - Constructor Inheritance: Constructors are not inherited by subclasses. However, you can use the
super()
keyword to call the constructor of the superclass.
Example:
class Animal {
String name;
Animal(String name) {
this.name = name;
}
void eat() {
System.out.println(name + " is eating.");
}
}
class Dog extends Animal {
Dog(String name) {
super(name);
}
void bark() {
System.out.println(name + " is barking.");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog("Buddy");
myDog.eat(); // Inherited method
myDog.bark(); // Subclass method
}
}
In this example, the Dog
class inherits the name
property and eat
method from the Animal
class, demonstrating the concept of inheritance.
Method Overriding
Method Overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. This feature is essential for achieving runtime polymorphism, allowing methods to have the same name but different behaviors based on the object.
Rules for Method Overriding:
- Method Signature: The method name, parameter types, and return type must be identical in both the superclass and subclass.
- Access Modifier: The access modifier of the overriding method can only be more accessible or the same as the overridden method. For example, if the superclass method is
protected
, the subclass method can beprotected
orpublic
, but notprivate
. - Exception Handling: The subclass method can declare fewer or none of the exceptions declared by the superclass method. However, it cannot declare a checked exception that the superclass method does not declare.
- Final Methods: A method declared as
final
in the superclass cannot be overridden in the subclass. - Static Methods: A static method cannot be overridden. However, it can be hidden in the subclass.
Syntax:
class SuperClass {
void display() {
System.out.println("This is a method in superclass.");
}
}
class SubClass extends SuperClass {
@Override
void display() {
System.out.println("This is a method in subclass.");
}
}
Key Differences Between Overloading and Overriding:
- Method Name and Parameters: Overloaded methods must have different signatures (different parameter lists or different types of parameters). Overridden methods must have the same name and parameter list.
- Return Type: In method overloading, return types can be different. In method overriding, return types must be the same or covariant.
- Occurrence: Method overloading can occur within a class. Overriding occurs when a subclass provides a specific implementation of a method defined in its superclass.
- Polymorphism: Method overloading is compile-time polymorphism, whereas method overriding is runtime polymorphism.
Example:
class Vehicle {
void start() {
System.out.println("Vehicle started.");
}
}
class Car extends Vehicle {
@Override
void start() {
System.out.println("Car started.");
}
}
public class Main {
public static void main(String[] args) {
Vehicle myVehicle = new Vehicle();
myVehicle.start(); // Output: Vehicle started.
Vehicle myCar = new Car();
myCar.start(); // Output: Car started.
}
}
In this example, the Car
class overrides the start
method of the Vehicle
class. When the start
method is called on an object of type Car
, the overridden method in the Car
class is executed, demonstrating runtime polymorphism.
Conclusion
Online Code run
Step-by-Step Guide: How to Implement Java Programming Inheritance and Method Overriding
Topic: Java Programming - Inheritance and Method Overriding
1. Understanding Inheritance
Inheritance is one of the core concepts in Object-Oriented Programming (OOP). It allows a class to inherit the fields and methods of another class. The class that inherits is known as the subclass (or derived class), and the class from which it inherits is known as the superclass (or base class).
2. Creating a Superclass
First, let's create a superclass named Animal
.
public class Animal {
// Field
protected String type;
// Constructor
public Animal(String type) {
this.type = type;
}
// Method
public void sound() {
System.out.println("The animal makes a sound");
}
}
3. Creating a Subclass
Now, let's create a subclass named Dog
that inherits from the Animal
class.
public class Dog extends Animal {
// Additional field
private String breed;
// Constructor
public Dog(String type, String breed) {
super(type); // Calls the constructor of the superclass
this.breed = breed;
}
// Method
public void bark() {
System.out.println("The dog barks");
}
}
4. Testing Inheritance
Let's create a main class to test the inheritance.
public class Main {
public static void main(String[] args) {
// Create an object of Animal
Animal animal = new Animal("Generic Animal");
animal.sound(); // Output: The animal makes a sound
// Create an object of Dog
Dog dog = new Dog("Dog", "Labrador");
dog.sound(); // Output: The animal makes a sound
dog.bark(); // Output: The dog barks
}
}
5. Understanding Method Overriding
Method overriding is a feature that allows a subclass to provide a specific implementation of a method that is already defined in its superclass. The method in the subclass must have the same name, same parameters, and the same return type (or a covariant return type) as the method in the superclass.
6. Overriding a Method in the Subclass
Let's override the sound
method in the Dog
class.
public class Dog extends Animal {
// Additional field
private String breed;
// Constructor
public Dog(String type, String breed) {
super(type); // Calls the constructor of the superclass
this.breed = breed;
}
// Overriding method
@Override
public void sound() {
System.out.println("The dog barks");
}
// Method
public void bark() {
System.out.println("The dog barks");
}
}
7. Testing Method Overriding
Let's create a new main class to test the method overriding.
public class Main {
public static void main(String[] args) {
// Create an object of Animal
Animal animal = new Animal("Generic Animal");
animal.sound(); // Output: The animal makes a sound
// Create an object of Dog
Dog dog = new Dog("Dog", "Labrador");
dog.sound(); // Output: The dog barks
dog.bark(); // Output: The dog barks
}
}
8. Using the super
Keyword
The super
keyword refers to the superclass (parent) of the current object. We use super
to call a method in the parent class.
9. Example with super
Let's modify the Dog
class to use the super
keyword.
public class Dog extends Animal {
// Additional field
private String breed;
// Constructor
public Dog(String type, String breed) {
super(type); // Calls the constructor of the superclass
this.breed = breed;
}
// Overriding method
@Override
public void sound() {
super.sound(); // Calls the sound method of the superclass
System.out.println("The dog barks");
}
// Method
public void bark() {
System.out.println("The dog barks");
}
}
10. Testing the super
Keyword
Let's run the main class again to see the effect.
Top 10 Interview Questions & Answers on Java Programming Inheritance and Method Overriding
Top 10 Questions and Answers on Java Programming: Inheritance and Method Overriding
1. What is Inheritance in Java?
Example:
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
// Inherits the eat() method from Animal
}
public class TestInheritance {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // Output: This animal eats food.
}
}
2. What is Method Overriding in Java?
Answer:
Method overriding in Java occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. The method in the subclass must have the same name, return type, and parameters as the method in the superclass. Method overriding is a fundamental concept for runtime polymorphism.
Example:
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Dog barks");
}
}
public class TestInheritance {
public static void main(String[] args) {
Animal myAnimal = new Animal();
Animal myDog = new Dog();
myAnimal.makeSound(); // Output: Animal makes a sound
myDog.makeSound(); // Output: Dog barks
}
}
3. Can a Private Method in a Superclass be Overridden by a Subclass?
Answer:
No, a private method in a superclass cannot be overridden by a subclass. Since private methods are not accessible outside the class where they are defined, they cannot be seen by subclasses and, hence, cannot be overridden. A subclass can define a method with the same signature as a private method in a superclass, but it does not constitute method overriding.
Example:
class SuperClass {
private void display() {
System.out.println("SuperClass method");
}
}
class SubClass extends SuperClass {
// This is not overriding but a new method in SubClass
void display() {
System.out.println("SubClass method");
}
}
4. What is the Benefit of Using Inheritance in Java?
Answer:
The primary benefits of using inheritance in Java are:
- Code Reusability: Inherited fields and methods reduce the need to write duplicate code, making development faster.
- Hierarchy Management: Inheritance helps in defining a clear hierarchical structure between classes, which is useful for categorization and logical grouping.
- Maintainability: Changes made to a method in a superclass are automatically reflected in all subclasses, which simplifies maintenance and updates.
5. What is the Use of super
Keyword in Java?
Answer:
The super
keyword in Java is used to refer to the immediate parent class of the current class. It can be used to:
- Access the non-static data members of the superclass.
- Access the methods of the superclass (useful when the subclass and superclass have methods with the same name).
- Call the constructor of the superclass (using
super()
).
Example:
class SuperClass {
String name;
SuperClass(String name) {
this.name = name;
}
void display() {
System.out.println("Name from SuperClass: " + name);
}
}
class SubClass extends SuperClass {
String name;
SubClass(String name) {
super(name); // Calls the constructor of SuperClass
this.name = name;
}
void display() {
super.display(); // Calls the display() method of SuperClass
System.out.println("Name from SubClass: " + this.name);
}
}
public class TestSuper {
public static void main(String[] args) {
SubClass myObj = new SubClass("Java");
myObj.display();
// Output:
// Name from SuperClass: Java
// Name from SubClass: Java
}
}
6. Can a Subclass Override a Static Method in Java?
Answer:
Static methods cannot be overridden in Java. However, they can be hidden by a subclass, meaning that the subclass can provide a method with the same name and signature that seems to override it. This is called method hiding, not overriding.
Example:
class SuperClass {
static void staticMethod() {
System.out.println("Static method from SuperClass");
}
}
class SubClass extends SuperClass {
static void staticMethod() {
System.out.println("Static method from SubClass");
}
}
public class TestStaticMethod {
public static void main(String[] args) {
SuperClass.staticMethod(); // Output: Static method from SuperClass
SubClass.staticMethod(); // Output: Static method from SubClass
}
}
7. What is the Difference Between Overloading and Overriding in Java?
Answer:
Overloading and overriding are two mechanisms in Java for reusing methods, but they serve different purposes.
Overloading (Compile-time Polymorphism): It occurs when two or more methods in the same class have the same name but different parameters (different type, number, or both). The method to be invoked is determined at compile time based on the method signature.
Overriding (Runtime Polymorphism): It occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. The method to be invoked is determined at runtime, depending on the object being referred to.
Example of Overloading:
class MathOperations {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
Example of Overriding:
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Dog barks");
}
}
8. What are the Rules for Method Overriding in Java?
Answer:
The rules for method overriding in Java are as follows:
- Signature: The method in the subclass must have the same name, return type, and parameters as the method in the superclass.
- Access Level: The method in the subclass must have the same or a broader access level than the method in the superclass. For example, a private method cannot be overridden as it is not accessible.
- Exception Handling: The method in the subclass cannot throw a new or broader checked exception than the method in the superclass. It can throw fewer, narrower, or no exceptions.
- Final Methods: Methods marked with the
final
keyword cannot be overridden. - Abstract Methods: Abstract methods must be overridden in the subclass.
Example:
class SuperClass {
void display() throws IOException {
System.out.println("SuperClass method");
}
}
class SubClass extends SuperClass {
@Override
void display() throws FileNotFoundException { // Okay, since it's narrower
System.out.println("SubClass method");
}
}
9. Can a Subclass Override a Constructor?
Answer:
No, constructors cannot be overridden in Java. Constructors are not inherited, and each class must define its own constructors. However, a subclass can invoke the constructor of its superclass using the super()
call.
Example:
class SuperClass {
SuperClass() {
System.out.println("SuperClass Constructor");
}
}
class SubClass extends SuperClass {
SubClass() {
super(); // Calls the constructor of SuperClass
System.out.println("SubClass Constructor");
}
}
public class TestConstructor {
public static void main(String[] args) {
SubClass myObj = new SubClass();
// Output:
// SuperClass Constructor
// SubClass Constructor
}
}
10. What is a Concrete Method in Java?
Answer:
A concrete method in Java is a method that has an implementation or a body. Unlike abstract methods, which do not have an implementation and must be overridden by subclasses, concrete methods contain the actual code that defines the behavior of a method.
Example:
class Animal {
void eat() { // This is a concrete method
System.out.println("Animal eats food");
}
void breathe(); // This is an abstract method (compiler error, needs abstract class)
}
In Java, a class can have both abstract and concrete methods. If a class has at least one abstract method, it must be declared as an abstract class.
Example:
Login to post a comment.