Unit 2 Programs Java
Unit 2 Programs Java
Unit 2 Programs Java
PART-C
2. What is inheritance? How inheritance is implemented in java? Create a class
Book and define display method to display book information. Inherit
Reference_Book and Magazine classes from Book class and override display
method of Book class in Reference_Book and Magazine classes.
Make necessary assumptions required.(
// Base class: Book
class Book {
private String title;
private String author;
private String publisher;
private int publicationYear;
// Subclass 1: Reference_Book
class Reference_Book extends Book {
private int edition;
public Reference_Book(String title, String author, String publisher, int publicationYear, int
edition) {
super(title, author, publisher, publicationYear);
this.edition = edition;
}
// Subclass 2: Magazine
class Magazine extends Book {
private int issueNumber;
public Magazine(String title, String author, String publisher, int publicationYear, int
issueNumber) {
super(title, author, publisher, publicationYear);
this.issueNumber = issueNumber;
}
OUTPUT:
Book Information:
Title: The Great Gatsby
Author: F. Scott Fitzgerald
Publisher: Scribner
Publication Year: 1925
@Override
public double compoundInterest(double p, double r, double t) {
// Compound Interest formula: CI = P * (1 + R/100)^T - P
return p * (Math.pow(1 + r / 100, t)) - p;
}
}
// Set initial amount, annual interest rate (in percentage), and time period (in years)
double principal = 1000.0;
double rate = 5.0;
double time = 2.5;
@Override
void Reserve() {
System.out.println(numberOfSeats + " seats reserved in " + trainName + " train.");
}
}
@Override
void Reserve() {
System.out.println(numberOfSeats + " seats reserved in " + busName + " bus.");
}
}
PART-B
17. Declare an abstract class to represent a bank account with data members
name, account number, address and abstract methods withdraw and
deposit. Method display() is needed to show balance. Derive a subclass
Savings Account and add the following details: return on investment and
the method calcAmt() to show the amount in the account after 1
year.Create instance of Savings Account and show the use of withdraw
and deposit abstract methods
@Override
void withdraw(double amount) {
balance -= amount;
}
@Override
void deposit(double amount) {
balance += amount;
}
}
OUTPUT:
Balance: 1300.0
Amount after 1 year: 1365.0
UNIT-II
PART-B
12.
class Calculator {
int num1, num2;
Calculator(int a, int b) {
num1 = a;
num2 = b;
}
void add() {
System.out.println("Addition result: " + (num1 + num2));
}
}
void subtract() {
System.out.println("Subtraction result: " + (num1 - num2));
}
}
void multiply() {
System.out.println("Multiplication result: " + (num1 * num2));
}
}