0% found this document useful (0 votes)
20 views31 pages

Diamond Problem and Interface Concept in Java

The Diamond Problem in Java arises during multiple inheritance when a child class inherits methods from two parent classes with the same signature, causing ambiguity. This issue can be resolved using interfaces, which allow for multiple inheritance without conflict, as well as by explicitly overriding methods in implementing classes. The document also discusses various scenarios related to the Diamond Problem, including resolving conflicts between default methods and abstract methods in interfaces.

Uploaded by

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

Diamond Problem and Interface Concept in Java

The Diamond Problem in Java arises during multiple inheritance when a child class inherits methods from two parent classes with the same signature, causing ambiguity. This issue can be resolved using interfaces, which allow for multiple inheritance without conflict, as well as by explicitly overriding methods in implementing classes. The document also discusses various scenarios related to the Diamond Problem, including resolving conflicts between default methods and abstract methods in interfaces.

Uploaded by

leelarani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Diamond Problem in Java

Diamond Problem is a problem faced during Multiple Inheritance in Java

What is a Diamond Problem in Java?


Inheritance in Java is when a child class inherits the properties of the parent
class. There are certain types of inheritance in Java as mentioned below:
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance

Talking about Multiple inheritance is when a child class is inherits the


properties from more than one parents and the methods for the parents are
same (Method name and parameters are exactly the same) then child gets
confused about which method will be called. This problem in Java is called
the Diamond problem.

Example of Java Diamond Problem


// Java Program to demonstrate

// Diamond Problem

import java.io.*;

// Parent Class1

class Parent1 {

void fun() { System.out.println("Parent1"); }

}
// Parent Class2

class Parent2 {

void fun() { System.out.println("Parent2"); }

// Inherting the Properties from

// Both the classes

class test extends Parent1, Parent2 {

// main function

public static void main(String[] args)

test t = new test();

t.fun();

Output:

Error
Explanation : In above example we have seen that “test” class is extending two
classes “Parent1 ” and “Parent2” and its calling function “fun()” which is
defined in both parent classes so now here it got confused which definition it
should inherit.

Solution of Diamond Problem in Java

Although Diamond Problem is a serious issue but we can create a solution for it
which is Interface. Interface are created by using interface keyword. It contains
all methods by default as abstract we don’t need to declared as abstract ,compiler
will do it implicitly.

// Java Programs to illustrate

// use of Interface to solve

// Diamond Problem

import java.io.*;
// Interfaces Declared

interface Parent1 {

void fun();

// Interfaces Declared

interface Parent2 {

void fun();

// Inheritance using Interfaces

class test implements Parent1, Parent2 {

public void fun()

System.out.println("fun function");

// Driver Class

class test1 {

// main function

public static void main(String[] args)

{
test t = new test();

t.fun();

Output
fun function

Another Solution???????????

public class A {
public void foo() {
System.out.println("Method foo() from class A");
}
}

public class B {
public void foo() {
System.out.println("Method foo() from class B");
}
}

public class C extends A, B {


public void bar() {
super.A.foo(); // Call the foo() method from class A
}
}

Java Interface

An Interface in Java programming language is defined as an abstract type used


to specify the behavior of a class. An interface in Java is a blueprint of a
behavior. A Java interface contains static constants and abstract methods.
 The interface in Java is a mechanism to achieve abstraction.
 By default, variables in an interface are public, static, and final.
 It is used to achieve abstraction and multiple inheritances in Java.
 It is also used to achieve loose coupling.
 In other words, interfaces primarily define methods that other classes must
implement.
 An interface in Java defines a set of behaviors that a class can implement,
usually representing an IS-A relationship, but not always in every scenario.

Syntax
interface {
// declare constant fields
// declare methods that abstract
// by default.
}

Relationship Between Class and Interface


A class can extend another class, and similarly, an interface can extend another
interface. However, only a class can implement an interface, and the reverse (an
interface implementing a class) is not allowed.

Difference Between Class and Interface


Multiple Inheritance in Java Using Interface
Multiple Inheritance is an OOPs concept that can’t be implemented in Java using
classes. But we can use multiple inheritances in Java using Interface.

import java.io.*;
// Add interface

interface Add{

int add(int a,int b);

// Sub interface

interface Sub{

int sub(int a,int b);

// Calculator class implementing

// Add and Sub

class Cal implements Add , Sub

// Method to add two numbers

public int add(int a,int b){

return a+b;

// Method to sub two numbers

public int sub(int a,int b){

return a-b;

}
}

class GFG{

// Main Method

public static void main (String[] args)

// instance of Cal class

Cal x = new Cal();

System.out.println("Addition : " + x.add(2,1));

System.out.println("Substraction : " + x.sub(2,1));

Output
Addition : 3
Substraction : 1

Another feature that was added in JDK 8 is that we can now define static methods
in interfaces that can be called independently without an object. These methods
are not inherited.

interface TestInterface
{

final int a = 10;

static void display()

System.out.println("hello");

// A class that implements the interface.

class TestClass implements TestInterface

// Driver Code

public static void main (String[] args)

TestInterface.display();

Output
hello

Extending Interfaces
interface A {

void method1();

void method2();

// B now includes method1

// and method2

interface B extends A {

void method3();

// the class must implement

// all method of A and B.

class GFG implements B

public void method1() {

System.out.println("Method 1");

public void method2() {

System.out.println("Method 2");

}
public void method3() {

System.out.println("Method 3");

public static void main(String[] args){

// Instance of GFG class created

GFG x = new GFG();

// All Methods Called

x.method1();

x.method2();

x.method3();

Output???

Output
Method 1
Method 2
Method 3

1. Scenario: Resolving Conflicting Default Methods in Multiple Interfaces

Question:
You have two interfaces, InterfaceA and InterfaceB, both defining a default
method printMessage(). If a class MyClass implements both interfaces, how can
you resolve the Diamond Problem?

Answer:
Since both interfaces provide a default method with the same signature, Java will
throw a compilation error unless MyClass explicitly overrides printMessage(). The
solution is to override the method and specify which interface's method should
be used using InterfaceName.super.method().

Code Solution
interface InterfaceA {
default void printMessage() {
System.out.println("Message from Interface A");
}
}

interface InterfaceB {
default void printMessage() {
System.out.println("Message from Interface B");
}
}

class MyClass implements InterfaceA, InterfaceB {


// Resolving the Diamond Problem
@Override
public void printMessage() {
InterfaceA.super.printMessage(); // Call InterfaceA's method
InterfaceB.super.printMessage(); // Call InterfaceB's method
System.out.println("Message from MyClass");
}
}

public class Main {


public static void main(String[] args) {
MyClass obj = new MyClass();
obj.printMessage();
}
}

Expected Output:
Message from Interface A
Message from Interface B
Message from MyClass

2. Scenario: Overriding Methods from Abstract Interfaces

Question:
Suppose you have two interfaces, X and Y, both declaring an abstract method
show(). A class Z implements both interfaces. What will happen, and how do you
resolve it?

Answer:
Since interfaces X and Y only declare abstract methods (without default
implementations), no ambiguity occurs. The implementing class Z must override
the method.

Code Solution
interface X {
void show(); // Abstract method
}

interface Y {
void show(); // Abstract method
}

class Z implements X, Y {
// Must override the show() method
@Override
public void show() {
System.out.println("Implemented show() in Z");
}
}

public class Main {


public static void main(String[] args) {
Z obj = new Z();
obj.show();
}
}
Expected Output:

Implemented show() in Z

3. Scenario: Diamond Problem with Class and Interface Combination

Question:
What happens if a class extends another class while also implementing an interface
that has a method with the same name?

Consider BaseClass having a method display() and an interface InterfaceC also


defining display(). A class ChildClass extends BaseClass and implements
InterfaceC. How can you resolve the conflict?

Answer:
Java gives priority to class methods over interface default methods. If
BaseClass has a method display(), it automatically overrides the interface's
default method.

Code Solution
class BaseClass {
public void display() {
System.out.println("Display from BaseClass");
}
}

interface InterfaceC {
default void display() {
System.out.println("Display from InterfaceC");
}
}

class ChildClass extends BaseClass implements InterfaceC {


// No need to override display() unless needed, BaseClass method takes
precedence
}

public class Main {


public static void main(String[] args) {
ChildClass obj = new ChildClass();
obj.display();
}
}

Expected Output:

Display from BaseClass

4. Scenario: Diamond Problem in Multi-Level Interface Inheritance

Question:
Consider three interfaces: A, B, and C. B and C both extend A, and a class D
implements both B and C. If A has a default method greet(), will there be a
Diamond Problem?

Answer:
Since B and C both inherit greet() from A and do not override it, D will directly
inherit greet() from A. There is no conflict unless B or C override greet(), in which
case D must explicitly override it.

Code Solution
interface A {
default void greet() {
System.out.println("Greet from A");
}
}

interface B extends A {}

interface C extends A {}

class D implements B, C {
// No need to override greet() since A provides it
}

public class Main {


public static void main(String[] args) {
D obj = new D();
obj.greet();
}
}

Expected Output:

Greet from A

5. Scenario: Avoiding Diamond Problem Using Static Methods

Question:
Can static methods in interfaces cause a Diamond Problem? Consider two
interfaces, M and N, both defining a static method info(). If a class P implements
both, what will happen?

Answer:
Static methods in interfaces do not cause a Diamond Problem because they
belong to the interface itself and cannot be overridden. To call them, use
InterfaceName.methodName().

Code Solution
interface M {
static void info() {
System.out.println("Info from M");
}
}

interface N {
static void info() {
System.out.println("Info from N");
}
}

class P {
void show() {
M.info(); // Calling static method of M
N.info(); // Calling static method of N
}
}
public class Main {
public static void main(String[] args) {
P obj = new P();
obj.show();
}
}

Expected Output:

Info from M
Info from N

Summary of Key Concepts


Scenario Key Learning

1. Conflicting default Use InterfaceName.super.method() to resolve


methods ambiguity.

2. Abstract methods in No ambiguity since the class must implement the


interfaces method.

3. Class & Interface Class method takes priority over interface default
method conflict methods.

4. Multi-level interface No conflict if only one interface provides a default


inheritance method.

5. Static methods in No Diamond Problem as static methods belong to the


interfaces interface itself.

Programs in Interface:
1. Define an interface “QueueOperations” which declares methods for a static queue. Define a class
“MyQueue” which contains an array and front and rear as data members and implements the above
interface. Initialize the queue using a constructor. Write the code to perform operations on a queue
object.
2. Write a java class called ‘student’ with name, and rollno. Write a class ‘Result’ to get Marks of 3 subjects
and another class “Sports’ to get the points obtained in sports. Calculate the total Marks and displays the
result (pass or fail) with points obtained in sports for three students using inheritance and constructor.
3. Define an abstract class “car” with members reg_no, model, reg_date. Define two subclasses of this class
– “transportVehicles ” (validity_no, start_date, period) and “privateVehicle ” (owner_name,
owner_address). Define appropriate constructors. Create n objects which could be of either
transportVehicles or privateVehicle class by asking the user’s choice. Display details of all
“privateVehicle” objects and all “transportVehicles” objects.
4. Create an interface “CreditCardInterface” with methods to viewCreditAmount, viewPin, changePin and
payBalance. Create a class Customer (name, card number, pin, creditAmount – initialized to 0).
Implement methods of the interface “CreditCardInterface” in Customer class. Create an array of
customer objects and perform the following actions.
a. Pay Balance
b. Change Pin
5. Develop a Java application with employee class includes emp_name, emp_id, address, mail_id,
mobile_no as members.
a. Inherit the classes Programmer, Assistant Professor from employee class.
b. Add Basic Pay as the member of all the inherited classes with 97% of BP as DA, 10% of BP
as HRA, 12% of BP as PF, 0.1% of BP for staff club fund.
c. Generate the pay slips for the employees with their gross and net salary.
6. Create a Java application to find the area of different shapes using abstract class.
Use the abstract class Shape that include two integers and an empty method named printArea().
Construct the classes Rectangle, Triangle and Circle inherited from the class Shape. The Derived classes
should include only the method printArea() that print the area of the given shape.

7. A vehicle rental company rents out different types of vehicles, such as Car, Truck, and Bike. Each type of
vehicle has different pricing rules for renting it. We will use runtime polymorphism to call the rent()
method for different vehicle types, and compile-time polymorphism to calculate the rental for multiple
days or hours.
8. In an employee payroll system, we have multiple types of employees (Manager, Developer, and Intern).
Each type of employee has different methods to calculate their salary based on their type and work
hours. The salary calculation is done using polymorphism, where each employee type overrides a
calculateSalary() method.
9. In a shape drawing application, there are various shapes like Circle, Rectangle, and Triangle. Each shape
has a draw() method, but the implementation of drawing the shape is different for each one. Using
polymorphism, the application should be able to call the draw() method on different shapes through a
common reference.
10.Bank Account System with Encapsulation
Design a BankAccount class that encapsulates the details of a bank account, such as the account holder's
name, account number, and balance. Provide the following methods:

i. Deposit: Allows depositing money into the account.


ii. Withdraw: Allows withdrawing money from the account, ensuring that the balance
doesn’t go below zero.
iii. Getters and Setters: Provide access to the account holder’s name, account number,
and balance through getters and setters.
iv. Display Details: Display the account holder’s name, account number, and balance.

11.Student Class with Encapsulation


Create a Student class that encapsulates the student's details (name, roll number, and marks).
Provide the following methods:
i. Setters: Set the student's details (name, roll number, and marks).
ii. Getters: Get the student's details.
iii. Update Marks: Method to update the student's marks (ensuring the marks remain
between 0 and 100).
iv. Display: Method to display the student's name, roll number, and marks.
12.Product Class with Encapsulation
Create a Product class with private fields: productName, productCode, and price. Provide
the following methods:
i. Setters: Set the values of product name, code, and price.
ii. Getters: Get the values of product name, code, and price.
iii. Discount: Apply a discount to the product’s price (the discount should not reduce
the price below 0).
iv. Display Product Details: Method to display product name, product code, and
final price after discount.

These Java programs cover essential OOP concepts like inheritance, polymorphism,
encapsulation, and abstraction. Below are solutions with explanations for each scenario.

1. Implementing Queue Operations Using Interface

This program demonstrates how to define an interface for queue operations and implement it in
a class.

Code
// Interface defining queue operations
interface QueueOperations {
void enqueue(int item);
int dequeue();
void display();
}

// Class implementing the queue


class MyQueue implements QueueOperations {
private int[] queue;
private int front, rear, size;

// Constructor to initialize queue


public MyQueue(int size) {
this.size = size;
queue = new int[size];
front = -1;
rear = -1;
}
// Enqueue operation
public void enqueue(int item) {
if (rear == size - 1) {
System.out.println("Queue is full");
return;
}
if (front == -1) front = 0;
queue[++rear] = item;
System.out.println(item + " added to queue");
}

// Dequeue operation
public int dequeue() {
if (front == -1 || front > rear) {
System.out.println("Queue is empty");
return -1;
}
return queue[front++];
}

// Display queue
public void display() {
if (front == -1 || front > rear) {
System.out.println("Queue is empty");
return;
}
System.out.print("Queue elements: ");
for (int i = front; i <= rear; i++) {
System.out.print(queue[i] + " ");
}
System.out.println();
}

public static void main(String[] args) {


MyQueue q = new MyQueue(5);
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
q.display();
System.out.println("Dequeued: " + q.dequeue());
q.display();
}
}

Explanation

 QueueOperations defines an interface for queue methods.


 MyQueue implements the queue using an array.
 enqueue() inserts an item, dequeue() removes it, and display() prints the queue contents.

Output

10 added to queue
20 added to queue
30 added to queue
Queue elements: 10 20 30
Dequeued: 10
Queue elements: 20 30

2. Student Result Calculation Using Inheritance

This program calculates the total marks and result by using multiple classes.

Code
// Student class with name and roll number
class Student {
String name;
int rollNo;

public Student(String name, int rollNo) {


this.name = name;
this.rollNo = rollNo;
}
}

// Result class to store marks


class Result extends Student {
int subject1, subject2, subject3;

public Result(String name, int rollNo, int s1, int s2, int s3) {
super(name, rollNo);
subject1 = s1;
subject2 = s2;
subject3 = s3;
}

public int totalMarks() {


return subject1 + subject2 + subject3;
}

public boolean isPass() {


return subject1 >= 35 && subject2 >= 35 && subject3 >= 35;
}
}

// Sports class to store sports points


class Sports extends Result {
int sportsPoints;

public Sports(String name, int rollNo, int s1, int s2, int s3, int points)
{
super(name, rollNo, s1, s2, s3);
sportsPoints = points;
}

public void displayResult() {


System.out.println("Student: " + name + " (Roll No: " + rollNo + ")");
System.out.println("Total Marks: " + totalMarks());
System.out.println("Result: " + (isPass() ? "Pass" : "Fail"));
System.out.println("Sports Points: " + sportsPoints);
}
}

public class Main {


public static void main(String[] args) {
Sports s1 = new Sports("Alice", 101, 78, 45, 89, 8);
Sports s2 = new Sports("Bob", 102, 30, 40, 20, 6);
s1.displayResult();
s2.displayResult();
}
}

Explanation

 Student stores student details.


 Result calculates total marks and determines pass/fail.
 Sports extends Result to include sports points.

Output

Student: Alice (Roll No: 101)


Total Marks: 212
Result: Pass
Sports Points: 8

Student: Bob (Roll No: 102)


Total Marks: 90
Result: Fail
Sports Points: 6

3. Car Abstract Class with Subclasses

This program demonstrates abstract classes and object creation at runtime.

Code
import java.util.Scanner;

// Abstract class Car


abstract class Car {
String regNo, model, regDate;

public Car(String regNo, String model, String regDate) {


this.regNo = regNo;
this.model = model;
this.regDate = regDate;
}

abstract void display();


}

// TransportVehicle subclass
class TransportVehicle extends Car {
String validityNo, startDate, period;

public TransportVehicle(String regNo, String model, String regDate, String


validityNo, String startDate, String period) {
super(regNo, model, regDate);
this.validityNo = validityNo;
this.startDate = startDate;
this.period = period;
}

void display() {
System.out.println("Transport Vehicle - " + model + ", Reg No: " +
regNo);
}
}

// PrivateVehicle subclass
class PrivateVehicle extends Car {
String ownerName, ownerAddress;

public PrivateVehicle(String regNo, String model, String regDate, String


ownerName, String ownerAddress) {
super(regNo, model, regDate);
this.ownerName = ownerName;
this.ownerAddress = ownerAddress;
}

void display() {
System.out.println("Private Vehicle - " + model + ", Owner: " +
ownerName);
}
}

public class Main {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Car[] vehicles = new Car[3];

vehicles[0] = new TransportVehicle("TN01AB1234", "Truck", "2022-01-


15", "V123", "2022-01-01", "5 years");
vehicles[1] = new PrivateVehicle("TN02CD5678", "Sedan", "2023-03-20",
"John Doe", "Chennai");
vehicles[2] = new TransportVehicle("TN03EF9101", "Bus", "2021-07-10",
"V567", "2021-06-10", "10 years");

System.out.println("Transport Vehicles:");
for (Car c : vehicles) {
if (c instanceof TransportVehicle) c.display();
}

System.out.println("\nPrivate Vehicles:");
for (Car c : vehicles) {
if (c instanceof PrivateVehicle) c.display();
}
}
}

Explanation

 Car is an abstract class.


 TransportVehicle and PrivateVehicle extend Car.
 Objects are created based on user choice.

Output

Transport Vehicles:
Transport Vehicle - Truck, Reg No: TN01AB1234
Transport Vehicle - Bus, Reg No: TN03EF9101

Private Vehicles:
Private Vehicle - Sedan, Owner: John Doe

4. Credit Card System Using Interface

This program implements a credit card system using an interface and an array of customers.

Code
import java.util.Scanner;

// Interface for credit card operations


interface CreditCardInterface {
void viewCreditAmount();
void viewPin();
void changePin(int newPin);
void payBalance(double amount);
}

// Customer class implementing CreditCardInterface


class Customer implements CreditCardInterface {
String name;
String cardNumber;
private int pin;
private double creditAmount;
public Customer(String name, String cardNumber, int pin) {
this.name = name;
this.cardNumber = cardNumber;
this.pin = pin;
this.creditAmount = 0; // Default credit amount
}

public void viewCreditAmount() {


System.out.println(name + "'s Credit Amount: $" + creditAmount);
}

public void viewPin() {


System.out.println("PIN: " + pin);
}

public void changePin(int newPin) {


this.pin = newPin;
System.out.println("PIN changed successfully!");
}

public void payBalance(double amount) {


if (amount > 0) {
creditAmount += amount;
System.out.println("Amount paid: $" + amount);
} else {
System.out.println("Invalid amount!");
}
}
}

public class Main {


public static void main(String[] args) {
Customer[] customers = {
new Customer("Alice", "1234-5678-9876-5432", 1111),
new Customer("Bob", "5678-1234-4321-8765", 2222)
};

customers[0].payBalance(500);
customers[0].viewCreditAmount();
customers[0].changePin(9999);
}
}

Explanation

 CreditCardInterface defines methods for a credit card system.


 Customer class implements this interface and modifies credit balance and PIN.

Output

Amount paid: $500.0


Alice's Credit Amount: $500.0
PIN changed successfully!
5. Employee Payroll System Using Inheritance

This program calculates salaries for employees, demonstrating inheritance.

Code
// Employee base class
class Employee {
String empName, empId, address, mailId;
long mobileNo;
double basicPay;

public Employee(String name, String id, String addr, String mail, long
mobile, double basicPay) {
this.empName = name;
this.empId = id;
this.address = addr;
this.mailId = mail;
this.mobileNo = mobile;
this.basicPay = basicPay;
}

public double calculateGrossSalary() {


double DA = 0.97 * basicPay;
double HRA = 0.10 * basicPay;
return basicPay + DA + HRA;
}

public double calculateNetSalary() {


double PF = 0.12 * basicPay;
double staffFund = 0.001 * basicPay;
return calculateGrossSalary() - (PF + staffFund);
}

public void displayPaySlip() {


System.out.println("Employee: " + empName);
System.out.println("Gross Salary: " + calculateGrossSalary());
System.out.println("Net Salary: " + calculateNetSalary());
}
}

// Programmer subclass
class Programmer extends Employee {
public Programmer(String name, String id, String addr, String mail, long
mobile, double basicPay) {
super(name, id, addr, mail, mobile, basicPay);
}
}

// AssistantProfessor subclass
class AssistantProfessor extends Employee {
public AssistantProfessor(String name, String id, String addr, String
mail, long mobile, double basicPay) {
super(name, id, addr, mail, mobile, basicPay);
}
}
public class Main {
public static void main(String[] args) {
Employee emp1 = new Programmer("Alice", "P001", "Chennai",
"[email protected]", 9876543210L, 40000);
Employee emp2 = new AssistantProfessor("Bob", "AP002", "Bangalore",
"[email protected]", 8765432109L, 50000);

emp1.displayPaySlip();
emp2.displayPaySlip();
}
}

Explanation

 Employee is a base class.


 Programmer and AssistantProfessor inherit from Employee.
 Methods calculate gross and net salary.

Output

Employee: Alice
Gross Salary: 87400.0
Net Salary: 82600.0

Employee: Bob
Gross Salary: 108500.0
Net Salary: 102900.0

6. Finding Area Using Abstract Class

This program demonstrates abstraction for calculating area of shapes.

Code
abstract class Shape {
abstract void printArea();
}

// Rectangle subclass
class Rectangle extends Shape {
int length, width;

public Rectangle(int l, int w) {


length = l;
width = w;
}

void printArea() {
System.out.println("Rectangle Area: " + (length * width));
}
}
// Circle subclass
class Circle extends Shape {
int radius;

public Circle(int r) {
radius = r;
}

void printArea() {
System.out.println("Circle Area: " + (Math.PI * radius * radius));
}
}

public class Main {


public static void main(String[] args) {
Shape rect = new Rectangle(10, 5);
Shape circle = new Circle(7);

rect.printArea();
circle.printArea();
}
}

Explanation

 Shape is an abstract class.


 Rectangle and Circle implement printArea().

Output

Rectangle Area: 50
Circle Area: 153.93804002589985

7. Vehicle Rental Using Polymorphism

This program demonstrates runtime polymorphism.

Code
class Vehicle {
void rent() {
System.out.println("Renting a vehicle");
}
}

// Car subclass
class Car extends Vehicle {
void rent() {
System.out.println("Renting a Car - $50 per day");
}
}

// Bike subclass
class Bike extends Vehicle {
void rent() {
System.out.println("Renting a Bike - $20 per day");
}
}

public class Main {


public static void main(String[] args) {
Vehicle v1 = new Car();
Vehicle v2 = new Bike();

v1.rent(); // Calls Car's rent()


v2.rent(); // Calls Bike's rent()
}
}

Explanation

 Vehicle class has a method rent().


 Car and Bike override rent().

Output

Renting a Car - $50 per day


Renting a Bike - $20 per day

8. Bank Account System Using Encapsulation

This program ensures data security in bank transactions.

Code
class BankAccount {
private String accountHolder;
private int accountNumber;
private double balance;

public BankAccount(String name, int accNum, double balance) {


this.accountHolder = name;
this.accountNumber = accNum;
this.balance = balance;
}

public void deposit(double amount) {


balance += amount;
System.out.println("Deposited: $" + amount);
}

public void withdraw(double amount) {


if (balance >= amount) {
balance -= amount;
System.out.println("Withdrawn: $" + amount);
} else {
System.out.println("Insufficient balance");
}
}

public void display() {


System.out.println("Account Holder: " + accountHolder);
System.out.println("Balance: $" + balance);
}
}

public class Main {


public static void main(String[] args) {
BankAccount acc = new BankAccount("Alice", 101, 1000);
acc.deposit(500);
acc.withdraw(300);
acc.display();
}
}

Explanation

 Encapsulation prevents direct access to data members.

Output

Deposited: $500
Withdrawn: $300
Account Holder: Alice
Balance: $1200

You might also like