0% found this document useful (0 votes)
29 views29 pages

Java Inheritance and Polymorphism Guide

Uploaded by

harishramaraops
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views29 pages

Java Inheritance and Polymorphism Guide

Uploaded by

harishramaraops
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CONCEPT 1 : INHERITANCE

[Link] INHERITANCE
class Animal {
String name;

public void eat() {


[Link](name + " is eating.");
}
}

class Dog extends Animal {


public void bark() {
[Link](name + " is barking.");
}
}

public class InheritanceDemo {


public static void main(String[] args) {
Dog dog = new Dog();
[Link] = "Buddy";
[Link](); // Inherited from Animal
[Link](); // Specific to Dog
}
}
OUTPUT :
Buddy is eating.
Buddy is barking.

2. METHOD OVERRIDING

class Vehicle {
public void move() {
[Link]("The vehicle is moving.");
}
}

class Car extends Vehicle {


@Override // Optional annotation for clarity
public void move() {
[Link]("The car is driving.");
}
}

public class InheritanceDemo {


public static void main(String[] args) {
Vehicle vehicle = new Vehicle();
[Link](); // Calls Vehicle's move()

Car car = new Car();


[Link](); // Calls Car's overridden move()
}
}
OUTPUT :
The vehicle is moving.
The car is driving.

3. SUPER KEYWORD

class Shape {
public void draw() {
[Link]("Drawing a shape.");
}
}

class Circle extends Shape {


@Override
public void draw() {
[Link](); // Call the superclass's draw()
[Link]("Drawing a circle.");
}
}

public class InheritanceDemo {


public static void main(String[] args) {
Circle circle = new Circle();
[Link]();
}
}
OUTPUT :
Drawing a shape.
Drawing a circle.

4. CONSTRUCTOR CHAINING

class Animal {
public Animal() {
[Link]("Animal constructor");
}
}

class Dog extends Animal {


public Dog() {
super(); // Call the superclass constructor implicitly
[Link]("Dog constructor");
}
}

public class InheritanceDemo {


public static void main(String[] args) {
Dog dog = new Dog();
}
}

OUTPUT :
Animal constructor
Dog constructor
5. ACCESS MODIFIERS

class Animal {
private String name; // Only accessible within Animal

public void eat() { // Accessible from anywhere


[Link](name + " is eating.");
}

// Getter method for private name field (encapsulation)


public String getName() {
return name;
}
}

class Dog extends Animal {


protected String breed; // Accessible within Dog and subclasses

public void bark() {


[Link](name + " (" + breed + ") is barking.");
// Access inherited name using getName() for better encapsulation
}
}

public class InheritanceDemo {


public static void main(String[] args) {
Dog dog = new Dog();
[Link] = "Fido"; // Now accessible due to being in the same
package
[Link] = "Golden Retriever";
[Link](); // Public access
[Link]("Dog's breed (using getter): " + [Link]());
// Access using getName()
}
}

OUTPUT :
/tmp/Ip8n0AJNSo/[Link][Link] error: name has private
access in Animal
[Link](name + " (" + breed + ") is barking.");
^
ERROR!
/tmp/Ip8n0AJNSo/[Link][Link] error: name has private
access in Animal
[Link] = "Fido"; // Now accessible due to being in the same
package
^
2 errors

6. INHERITANCE & POLYMORPHISM

interface AnimalInterface {
public void makeSound(); // Abstract method
}

class Cat implements AnimalInterface {


@Override
public void makeSound() {
[Link]("The cat meows.");
}
}

class Cow implements AnimalInterface {


@Override
public void makeSound() {
[Link]("The cow moos.");
}
}

public class InheritanceDemo {


public static void makeAnimalSound(AnimalInterface animal) {
[Link](); // Polymorphic call, actual behavior
determined at runtime
}

public static void main(String[] args) {


Cat cat = new Cat();
Cow cow = new Cow();

makeAnimalSound(cat); // Prints "The cat meows."


makeAnimalSound(cow); // Prints "The cow moos."
}
}
OUTPUT :
The cat meows.
The cow moos.

7. INHERITANCE AND ABSTRACTION

abstract class Animal {


public abstract void makeSound(); // Abstract method, subclasses
must implement
public String getName() {
return "Animal"; // Default implementation
}
}

class Cat extends Animal {


@Override
public void makeSound() {
[Link]("The cat meows.");
}
}
public class Main {
public static void main(String[] args) {
// Create an Animal object (e.g., a Cat)
Animal animal = new Cat();
[Link](); // This will print "The cat meows."
}
}
OUTPUT :
The cat meows.

8. HIERARCHICAL INHERITANCE

class Vehicle {
public void move() {
[Link]("The vehicle is moving.");
}
}

class Car extends Vehicle {


public void drive() {
[Link]("The car is driving.");
}
}

class Truck extends Vehicle {


public void haulCargo() {
[Link]("The truck is hauling cargo.");
}
}

public class InheritanceDemo {


public static void main(String[] args) {
Car car = new Car();
Truck truck = new Truck();
[Link](); // Inherited from Vehicle
[Link](); // Specific to Car

[Link](); // Inherited from Vehicle


[Link](); // Specific to Truck
}
}

OUTPUT :
The vehicle is moving.
The car is driving.
The vehicle is moving.
The truck is hauling cargo.

9. MULTIPLE INHERITANCE

class Animal {
public void eat() {
[Link]("The animal is eating.");
}
}

class Mammal extends Animal {


public void giveBirth() {
[Link]("The mammal is giving birth.");
}
}
class Dog extends Mammal {
public void bark() {
[Link]("The dog is barking.");
}
}

public class InheritanceDemo {


public static void main(String[] args) {
Dog dog = new Dog();
[Link](); // Inherited from Animal
[Link](); // Inherited from Mammal
[Link](); // Specific to Dog
}
}

OUTPUT:
The animal is eating.
The mammal is giving birth.
The dog is barking.

10. HYBRID INHERITANCE WITH INTERFACE

interface Movable {
public void move();
}

class Animal {
public void eat() {
[Link]("The animal is eating.");
}
}

class Vehicle implements Movable {


@Override
public void move() {
[Link]("The vehicle is moving.");
}
}

class FlyingAnimal extends Animal implements Movable {


@Override
public void move() {
[Link]("The flying animal is flying.");
}
}

public class InheritanceDemo {


public static void main(String[] args) {
Vehicle car = new Vehicle();
FlyingAnimal bird = new FlyingAnimal();

[Link](); // Implements Movable interface


[Link](); // Inherited from Animal
[Link](); // Overrides Animal's move() (polymorphism)
}
}
OUTPUT:
The vehicle is moving.
The animal is eating.
The flying animal is flying.
CONCEPT 2 : POLYMORPHISM

[Link] TIME POLYMORPHISM

class Calculator {
public int add(int a, int b) {
return a + b;
}

public double add(double a, double b) {


return a + b;
}
}

public class Main {


public static void main(String[] args) {
Calculator calc = new Calculator();
[Link]([Link](5, 3)); // Calls int add(int, int)
[Link]([Link](5.2, 7.8)); // Calls double add(double,
double)
}
}

OUTPUT:
8
13.0
2. RUNTIME POLYMORPHISM

class Animal {
public void makeSound() {
[Link]("Generic animal sound");
}
}

class Dog extends Animal {


@Override // Explicitly indicate overriding
public void makeSound() {
[Link]("Woof!");
}
}

public class Main {


public static void main(String[] args) {
Animal animal = new Animal(); // Can refer to any subclass at
runtime
[Link](); // Outputs: Generic animal sound

Animal dogAnimal = new Dog(); // Upcasting (polymorphism)


[Link](); // Outputs: Woof! (runtime
polymorphism)
}
}
OUTPUT:
Generic animal sound
Woof!

3. INTERFACE POLYMORPHISM

interface Drawable {
void draw();
}

class Square implements Drawable {


@Override
public void draw() {
[Link]("Drawing a square");
}
}

class Triangle implements Drawable {


@Override
public void draw() {
[Link]("Drawing a triangle");
}
}

public class Main {


public static void drawShape(Drawable shape) {
[Link](); // Polymorphism via interface
}
public static void main(String[] args) {
drawShape(new Square()); // Outputs: Drawing a square
drawShape(new Triangle()); // Outputs: Drawing a triangle
}
}

OUTPUT:
Drawing a square
Drawing a triangle

4. ABSTRACT CLASS AND POLYMORPHISM

abstract class Vehicle {


public abstract void move(); // Abstract method forces subclasses to
implement
}

class Car extends Vehicle {


@Override
public void move() {
[Link]("Car is driving");
}
}

class Bike extends Vehicle {


@Override
public void move() {
[Link]("Bike is cycling");
}
}

public class Main {


public static void moveVehicle(Vehicle vehicle) {
[Link](); // Polymorphism via abstract class
}

public static void main(String[] args) {


moveVehicle(new Car()); // Outputs: Car is driving
moveVehicle(new Bike()); // Outputs: Bike is cycling
}
}

OUTPUT :
Car is driving
Bike is cycling
CONCEPT 3 : ENCAPSULATION

[Link] PRIVATE VARIABLES

class Account {
private int balance; // Encapsulated data member
}

2. ACCESSING PRIVATE VARIABLES WITH GETTER


METHODS

class Account {
private int balance;

public int getBalance() {


return balance;
}
}

3. MODIFYING PRIVATE VARIABLES WITH SETTER


METHODS (VALIDATION EXAMPLE)

class Account {
private int balance;

public void setBalance(int amount) {


if (amount >= 0) {
balance = amount;
} else {
[Link]("Invalid balance: Cannot be negative.");
}
}
}

4. USING GETTERS AND SETTERS IN A SIMPLE PROGRAM

class Account {
private int balance;

public void setBalance(int amount) {


if (amount >= 0) {
balance = amount;
} else {
[Link]("Invalid balance: Cannot be negative.");
}
}

public int getBalance() {


return balance;
}
}

public class Main {


public static void main(String[] args) {
Account account = new Account();
[Link](100); // Setting balance using setter

int currentBalance = [Link](); // Retrieving balance using


getter
[Link]("Current balance: " + currentBalance);
}
}

OUTPUT :
Current balance: 100

5. READ-ONLY CLASS (USING ONLY GETTERS)

class Address {
private String street;
private String city;
private String state;
private String zipcode;

public Address(String street, String city, String state, String zipcode) {


[Link] = street;
[Link] = city;
[Link] = state;
[Link] = zipcode;
}

public String getStreet() {


return street;
}

public String getCity() {


return city;
}

public String getState() {


return state;
}

public String getZipcode() {


return zipcode;
}
}

public class Main {


public static void main(String[] args) {
// Create an Address object
Address address = new Address("123 Main St", "Anytown", "CA",
"12345");

// Print the address information using string concatenation


[Link]("Street: " + [Link]());
[Link]("City: " + [Link]());
[Link]("State: " + [Link]());
[Link]("Zipcode: " + [Link]());
}
}
OUTPUT:
Street: 123 Main St
City: Anytown
State: CA
Zipcode: 12345

6. CONSTRUCTOR WITH ENCAPSULATION

class Student {
private String name;
private int age;

public Student(String name, int age) {


if (age >= 0) { // Validation in constructor
[Link] = name;
[Link] = age;
} else {
[Link]("Invalid age: Cannot be negative.");
}
}

public String getName() {


return name;
}

public int getAge() {


return age;
}
}
public class Main {
public static void main(String[] args) {
// Create a Student object
Student student1 = new Student("Alice", 20);

// Print the student information


[Link]("Name: " + [Link]());
[Link]("Age: " + [Link]());
}
}

OUTPUT :
Name: Alice
Age: 20

7. FULL-FLEDGED PROGRAM WITH ENCAPSULATION

class Product {
private int id;
private String name;
private double price;

public Product(int id, String name, double price) {


[Link] = id;
[Link] = name;
[Link] = price;
}

public int getId() {


return id;
}

public String getName() {


return name;
}

public double getPrice() {


return price;
}

// Additional methods for product management (e.g., discount


calculation)
}

public class ProductStore {


public static void main(String[] args) {
Product product1 = new Product(101, "T-Shirt", 24.99);
Product product2 = new Product(102, "Jeans", 49.95);

[Link]("Product 1: " + [Link]() + " (ID: " +


[Link]() + ", Price: $" + [Link]() + ")");
[Link]("Product 2: " + [Link]() + " (ID: " +
[Link]() + ", Price: $" + [Link]() + ")");
}
}
OUTPUT:
Product 1: T-Shirt (ID: 101, Price: $24.99)
Product 2: Jeans (ID: 102, Price: $49.95)

CONCEPT 4 : ABSTRACTION

[Link] ABSTRACTION

abstract class Shape {


public abstract double getArea();
}

class Circle extends Shape {


private double radius;

public Circle(double radius) {


[Link] = radius;
}

@Override
public double getArea() {
return [Link] * radius * radius;
}
}

class Square extends Shape {


private double sideLength;

public Square(double sideLength) {


[Link] = sideLength;
}

@Override
public double getArea() {
return sideLength * sideLength;
}
}

public class Main {


public static void main(String[] args) {
Shape circle = new Circle(5);
Shape square = new Square(4);

[Link]("Circle Area: " + [Link]());


[Link]("Square Area: " + [Link]());
}
}

OUTPUT :
Circle Area: 78.53981633974483
Square Area: 16.0
2. INTERFACES FOR BEHAVIOR ABSTRACTION

interface Drawable {
void draw();
}

class Rectangle implements Drawable {


private double width, height;

public Rectangle(double width, double height) {


[Link] = width;
[Link] = height;
}

@Override
public void draw() {
[Link]("Drawing a rectangle with width: " + width + ",
height: " + height);
}
}

class Triangle implements Drawable {


private double base, height;

public Triangle(double base, double height) {


[Link] = base;
[Link] = height;
}

@Override
public void draw() {
[Link]("Drawing a triangle with base: " + base + ",
height: " + height);
}
}

public class Main {


public static void main(String[] args) {
Drawable rectangle = new Rectangle(5, 3);
Drawable triangle = new Triangle(4, 6);

[Link]();
[Link]();
}
}

OUTPUT:
Drawing a rectangle with width: 5.0, height: 3.0
Drawing a triangle with base: 4.0, height: 6.0

Common questions

Powered by AI

Interfaces support polymorphic behavior by allowing objects of various classes to be treated as instances of the interface they implement. This enables a form of polymorphism where a single action can trigger different behaviors in different objects. For an example, the 'Drawable' interface has a 'draw()' method that is implemented by both 'Square' and 'Triangle'. The polymorphic call of 'shape.draw()' invokes the respective 'draw()' method of the object (Square or Triangle) passed at runtime . This promotes code flexibility and reusability, as functions can operate on a wide variety of objects through a common interface .

Getters and setters contribute to encapsulation by providing controlled access to private fields, securing an object's attributes from external modification while allowing safe interactions. For example, in the 'Account' class, 'setBalance()' ensures the balance cannot be set to a negative value, while 'getBalance()' allows safe retrieval of the value . This approach maintains the integrity and validity of data and facilitates validation and logic control within the setter methods, ensuring reliable object state management and protecting against inadvertent errors or misuse.

Hierarchical inheritance provides flexibility by allowing multiple classes to inherit from a single parent class, facilitating code reuse and reducing redundancy. Each subclass can implement additional behaviors while inheriting the properties and methods of the common parent class. For instance, both 'Car' and 'Truck' classes inherit the 'move()' method from the 'Vehicle' class, allowing them to define specific functionalities such as 'drive()' for 'Car' and 'haulCargo()' for 'Truck', thus maintaining a clean, organized structure that can accommodate future growth and modifications .

The 'super' keyword is used in subclass method overriding to explicitly call a method from the superclass. This is significant because it allows the subclass to retain the behavior of the superclass method while extending or modifying it. For example, in the 'Circle' class, the 'draw()' method uses 'super.draw()' to invoke the 'Shape' class's 'draw()' method before executing additional subclass-specific functionality. This helps in maintaining a chain of execution that respects the hierarchy and behavior defined in the superclass .

Compile-time polymorphism, also known as static polymorphism, involves method overloading where multiple methods have the same name but differ in parameters. The method to be called is determined at compile time. For example, in the 'Calculator' class, the 'add' method is overloaded with different parameter types and signatures . In contrast, runtime polymorphism, or dynamic polymorphism, involves method overriding where a subclass overrides a method from its superclass, and the call to this overridden method is resolved at runtime. An instance of this is shown in the 'Dog' class where the 'makeSound()' method is overridden; the actual called method depends on the object type at runtime .

Access modifiers impact encapsulation by controlling the visibility and accessibility of class members. For example, the 'Animal' class uses a 'private' access modifier for the 'name' field, restricting access to the 'Animal' class only, thus enforcing encapsulation. This means external classes cannot directly modify the 'name' field, preserving data integrity. In contrast, 'protected' and 'public' modifiers allow for broader access, which can be necessary for subclass functionality as seen in the 'Dog' class accessing 'name' through a public getter method .

Constructor chaining enhances code reusability by ensuring that when a derived class is instantiated, the constructor of the base class is automatically called, allowing for initialization of inherited fields and properties. This process reduces code duplication and ensures that the base class's state is correctly initialized. For example, in the 'Dog' class, the constructor explicitly calls the 'Animal' class's constructor using the 'super()' keyword, ensuring all setup steps in the base class are executed, allowing the derived class to reuse the base class's initialization logic without additional code .

Encapsulation is considered crucial because it restricts direct access to some of an object's components and can protect the object's integrity by preventing outsiders from setting the internal data improperly. It allows for controlled access via public methods, known as getters and setters. For example, the 'Account' class uses private fields to encapsulate the balance and provides public methods to access ('getBalance()') or modify ('setBalance()') them under predefined conditions, maintaining data integrity and reducing unintended interference .

Abstract classes benefit object-oriented programming by providing a base class that defines common attributes and behaviors without giving full method implementations, forcing subclass implementation. This supports a design principle by focusing on 'what' a class does rather than 'how' it does it. For example, the abstract class 'Shape' declares the abstract method 'getArea()', prompting all subclasses like 'Circle' and 'Square' to offer specific implementations, ensuring method consistency and reducing duplication across the hierarchy .

Method overriding enhances polymorphism by allowing a subclass to provide a specific implementation of a method that is already defined in its superclass, thus enabling runtime polymorphism. This means that the method that is called at runtime is determined by the type of the object, allowing for dynamic method selection. For instance, in the example given, both the 'Vehicle' and 'Car' classes have a 'move()' method; however, 'Car' overrides it with a more specific implementation, demonstrating polymorphism where 'Car's move() method is called during runtime instead of 'Vehicle's .

You might also like