Java LAB EX-3 (Class and Object)
Java LAB EX-3 (Class and Object)
Procedure
INHERITANCE
It is a mechanism where one class (subclass or derived class) inherits the fields and methods of another class (superclass
or base class).
Define the Superclass: Create a class with common fields and methods that will be inherited by subclasses.
Define the Subclass: Create a subclass that extends the superclass using the extends keyword.
Instantiate the Subclass: Create an object of the subclass and use its methods, including those inherited from the
superclass.
Multiple Inheritance (Interface-based): A class implements multiple interfaces. Java does not support multiple
Hybrid Inheritance: A combination of two or more types of inheritance. Java supports hybrid inheritance through
Rules of Inheritance
Private Members: Private members of the superclass are not accessible directly in the subclass but can be accessed
Constructors: Constructors are not inherited but the superclass constructor can be called using super().
Method Overriding: Subclasses can override methods of the superclass to provide specific implementations.
final Keyword: Classes declared with final cannot be inherited. Methods declared as final cannot be overridden.
SYNTAX
Single Inheritance: Multilevel Inheritance:
class Superclass { class Superclass {
// Superclass code // Superclass code
} }
class Subclass extends Superclass { class IntermediateClass extends Superclass {
// Subclass code // Intermediate class code
} }
class Subclass extends IntermediateClass {
// Subclass code
}
Hierarchical Inheritance: Multiple Inheritance (Through Interfaces):
class Superclass { interface Interface1 {
// Superclass code // Interface1 methods
} }
class Subclass1 extends Superclass { interface Interface2 {
// Subclass1 code // Interface2 methods
} }
class Subclass2 extends Superclass { class Subclass implements Interface1, Interface2 {
// Subclass2 code // Implement methods from Interface1 and Interface2
} }
Hybrid Inheritance:
interface Interface1 {
// Interface1 methods
}
interface Interface2 {
// Interface2 methods
}
class Superclass {
// Superclass code
}
class Subclass1 extends Superclass implements Interface1 {
// Subclass1 code
}
class Subclass2 extends Superclass implements Interface2 {
// Subclass2 code
}
INTERFACE
Interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static
Interfaces cannot contain instance fields, constructors, or method implementations (except for default methods).
Declaration:
Implementation:
this.cardNumber = cardNumber;
this.cardHolderName = cardHolderName;
@Override
@Override
@Override
creditCardPayment.processPayment(250.00);
creditCardPayment.showTransactionDetails();
payPalPayment.processPayment(100.00);
payPalPayment.showTransactionDetails();
EXERCISE PROBLEM
1) Given a Book class and the Main class, write a MyBook class that does the following:
Inherits from Book, Has a parameterized constructor taking these 3 parameters:
string title
string author
int price
Implements the Book class' abstract display() method so it prints the title, author, and price.
Input Format
The Main class creates a Book object and calls the MyBook class constructor (passing it the necessary arguments). It then
calls the display method on the Book object.
Output Format
The void display() method should print and label the respective title, author, and price of the MyBook object's instance
(with each value on its own line).
Constraints
Strings and integers only.
Sample Input Sample Output
Sample Input Sample Output
love Title: love
jack Author: jack
300 Price: 300
2) Whether you fly for business or leisure purposes, you can choose either private jets or commercial airlines to get
from point A to point B. The task is to get the flight details and display them. Write a Java program to Implement this
task.
Create a class Aircraft and include the following data members/attributes
1.aircraftName as a string
2.source as string
3.destination as a string
Include a 3 argument constructor, Aircraft(String aircraftName, String source, String destination)
Include a method void displayDetails() to display details
Create a class PublicAircraft that extends Aircraft and include the following private attributes/data members
1.checkinbeforetwohours as boolean
2.noOfKgsallowed as integer
3.additionalFeedperkg as float
Create a class PrivateAircraft that extends Aircraft and include the following private attributes/data members
1.checkinbeforetwohours as boolean
2.pilotPreference as a string
3.purpose as a string
Each type of member gets a specific cashback amount for each order falling in a defined range. Details are given as below.
Use Inheritance and Overriding and write a program to Calculate the cashback amount calculateDiscount(), the customer
gets for the Bill Amount BA.
Input Format
First line of Input represents Name.
Second line of Input represents City.
Third of Input represents Age.
Fourth line of Input represents Gender.
Fifth line of Input represents Total Bill Amount.
Sixth line of Input represents 0 or 1 (0 for Basic Customer and 1 for Premium Customer)
if Premium Customer
Seventh line of Input represents Subscription amount.
Output Format
First line of Output represents Name.
Second line of Output represents City.
Third line of Output represents Age.
Fourth line of Output represents Gender
Fifth line of Output represents Total Bill Amount.
if Premium Customer
Sixth line of Output represents Subscription Amount.
Seventh line of Output represents Cash Back Amount.
If Basic Customer
Sixth line of Output represents Cash Back Amount.
Sample Input Sample Output
Joey Joey
cbe cbe
3 3
male male
2000 2000
0 100
4) Create multilevel inheritance with the below classes.
OfficerSal
method to calculate DA(98% of basic salary)
ManagerSal
method to calculate City allowance (20% of basic salary)
method to calculate Gross pay (basic salary + HRA + DA + City allowance)
Create Main class to get the employee ID , Name and Basic salary as input. Calculate HRA, DA, CA and Gross Salary.
Input Format
Employee code
Employee name
Salary
Output Format
Code
Name
Salary
HRA
DA
City Allowance
Gross Salary
Sample Input Sample Output
101 Name : Karthick
Karthick Salary 10000
10000 HRA :6000.0
Code :101 DA :9800.0
City Allowance :2000.0
Gross Salary :27800.0
5) Create 5 classes as shown in below diagram and create data members and methods as mentioned below.
Person
name and birthYear
Parameterized constructor and overload toString method
Student
department and attendance percentage
Parameterized constructor and overload toString method
method to calculate whether the student is eligible to attend the exam or not
Staff
salary
Parameterized constructor and overload toString method
TeachingStaff
subject and result percentage
Parameterized constructor and overload toString method
method to calculate new salary based on result percentage
NonTeachingStaff
Lab and experience
Parameterized constructor and overload toString method
method to calculate new salary based on experience
And create another child class StageEvent that extends Event with the following attribute,
SAMPLE PROGRAM:
Define the Base Class (Book):
class Book {
protected String title;
protected String author;
protected int publicationYear;
public Book(String title, String author, int publicationYear) {
this.title = title;
this.author = author;
this.publicationYear = publicationYear;
}
public void displayInfo() {
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.println("Publication Year: " + publicationYear);
}
}
Define the Derived Class (EBook) using Single Inheritance:
class EBook extends Book {
private double fileSize;
private String format;
public EBook(String title, String author, int publicationYear, double fileSize, String format) {
super(title, author, publicationYear);
this.fileSize = fileSize;
this.format = format;
}
public void displayInfo() {
super.displayInfo();
System.out.println("File Size: " + fileSize + " MB");
System.out.println("Format: " + format);
}
}
Define Another Derived Class (AudioBook) using Single Inheritance:
class AudioBook extends Book {
private double duration;
private String narrator;
public AudioBook(String title, String author, int publicationYear, double duration, String narrator) {
super(title, author, publicationYear);
this.duration = duration;
this.narrator = narrator;
}
public void displayInfo() {
super.displayInfo();
System.out.println("Duration: " + duration + " hours");
System.out.println("Narrator: " + narrator);
}
}
Demonstrate Hierarchical Inheritance:
public class LibraryManagementSystem {
public static void main(String[] args) {
Book book = new Book("The Great Gatsby", "F. Scott Fitzgerald", 1925);
EBook ebook = new EBook("Digital Fortress", "Dan Brown", 1998, 1.5, "PDF");
AudioBook audioBook = new AudioBook("Harry Potter and the Philosopher's Stone", "J.K. Rowling", 1997,
8.5, "Stephen Fry");
System.out.println("Book Details:");
book.displayInfo();
System.out.println("\nEBook Details:");
ebook.displayInfo();
System.out.println("\nAudioBook Details:");
audioBook.displayInfo();
}
}
Single Inheritance Multilevel Inheritance
// Superclass // Superclass
class Book { class LibraryItem {
String title; String id;
String author; String name;
public void displayInfo() { public void displayItem() {
System.out.println("Title: " + title); System.out.println("ID: " + id);
System.out.println("Author: " + author); System.out.println("Name: " + name);
} }
} }
// Subclass // Intermediate class
class EBook extends Book { class Book extends LibraryItem {
String downloadLink; String author;
public void displayDownloadLink() { public void displayAuthor() {
System.out.println("Download Link: " + System.out.println("Author: " + author);
downloadLink); }
} }
} // Subclass
public class SingleInheritanceDemo { class EBook extends Book {
public static void main(String[] args) { String downloadLink;
EBook ebook = new EBook(); public void displayDownloadLink() {
ebook.title = "Java Programming"; System.out.println("Download Link: " +
ebook.author = "John Doe"; downloadLink);
ebook.downloadLink = }
"http://example.com/download"; }
ebook.displayInfo(); public class MultilevelInheritanceDemo {
ebook.displayDownloadLink(); public static void main(String[] args) {
} EBook ebook = new EBook();
} ebook.id = "101";
ebook.name = "Advanced Java";
ebook.author = "Jane Doe";
ebook.downloadLink =
"http://example.com/advancedjava";
ebook.displayItem();
ebook.displayAuthor();
ebook.displayDownloadLink();
}
}
Hierarchical Inheritance Multiple Inheritance via Interfaces
// Superclass // Interface 1
class LibraryItem { interface Printable {
String id; void print();
String name; }
public void displayItem() { // Interface 2
System.out.println("ID: " + id); interface Borrowable {
System.out.println("Name: " + name); void borrow();
} }
} // Implementing multiple interfaces
// Subclass 1 class Magazine implements Printable, Borrowable {
class Book extends LibraryItem { String title;
String author; String publisher;
public void displayAuthor() {
System.out.println("Author: " + author); public void print() {
} System.out.println("Printing magazine: " + title);
} }
// Subclass 2 public void borrow() {
class Magazine extends LibraryItem { System.out.println("Borrowing magazine: " +
String publisher; title);
public void displayPublisher() { }
System.out.println("Publisher: " + publisher); }
} public class MultipleInheritanceDemo {
} public static void main(String[] args) {
public class HierarchicalInheritanceDemo { Magazine magazine = new Magazine();
public static void main(String[] args) { magazine.title = "Tech Monthly";
Book book = new Book(); magazine.publisher = "Tech Media";
book.id = "102"; magazine.print();
book.name = "Java Basics"; magazine.borrow();
book.author = "Alice"; }
Magazine magazine = new Magazine(); }
magazine.id = "201";
magazine.name = "Tech Monthly";
magazine.publisher = "Tech Media";
book.displayItem();
book.displayAuthor();
magazine.displayItem();
magazine.displayPublisher();
}
}
Hybrid Inheritance
// Superclass
class LibraryItem {
String id;
String name;
public void displayItem() {
System.out.println("ID: " + id);
System.out.println("Name: " + name);
}
}
// Interface
interface Downloadable {
void download();
}
// Subclass 1
class Book extends LibraryItem {
String author;
public void displayAuthor() {
System.out.println("Author: " + author);
}
}
// Subclass 2
class EBook extends Book implements
Downloadable {
String downloadLink;
public void download() {
System.out.println("Downloading from: " +
downloadLink);
}
}
public class HybridInheritanceDemo {
public static void main(String[] args) {
EBook ebook = new EBook();
ebook.id = "103";
ebook.name = "Learning Java";
ebook.author = "Bob";
ebook.downloadLink =
"http://example.com/learningjava";
ebook.displayItem();
ebook.displayAuthor();
ebook.download();
}
}
OUTPUT
RESULT