0% found this document useful (0 votes)
0 views14 pages

Java LAB EX-3 (Class and Object)

The document outlines a Java programming exercise focused on implementing inheritance and interfaces using classes and objects. It details various types of inheritance, rules for implementing interfaces, and provides example applications including a payment system and a flight details system. Additionally, it includes exercises for creating classes with specific attributes and methods, demonstrating the use of inheritance and method overriding.

Uploaded by

jayabalanakshaya
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)
0 views14 pages

Java LAB EX-3 (Class and Object)

The document outlines a Java programming exercise focused on implementing inheritance and interfaces using classes and objects. It details various types of inheritance, rules for implementing interfaces, and provides example applications including a payment system and a flight details system. Additionally, it includes exercises for creating classes with specific attributes and methods, demonstrating the use of inheritance and method overriding.

Uploaded by

jayabalanakshaya
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
You are on page 1/ 14

Ex:No: 3

Implement Inheritance and interface using class and objects


Date:
Aim
 To write a java program to implement inheritance and interface using class and objects

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.

Types of Inheritance in Java

Single Inheritance: A class inherits from one superclass.

Multilevel Inheritance: A class inherits from a subclass, creating a chain of inheritance.

Hierarchical Inheritance: Multiple classes inherit from a single superclass.

Multiple Inheritance (Interface-based): A class implements multiple interfaces. Java does not support multiple

inheritance of classes directly but achieves it through interfaces.

Hybrid Inheritance: A combination of two or more types of inheritance. Java supports hybrid inheritance through

interfaces but not through classes due to the ambiguity problem.

Rules of Inheritance

The extends Keyword: Used to create a subclass.

Private Members: Private members of the superclass are not accessible directly in the subclass but can be accessed

through public/protected getter methods.

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

methods, and nested types.

Interfaces cannot contain instance fields, constructors, or method implementations (except for default methods).

Rules for Java Interfaces:

Declaration:

1. Use the interface keyword.


2. Interfaces cannot have instance fields.
3. All methods in an interface are abstract by default (before Java 8). From Java 8 onwards, interfaces can
have default and static method.

Implementation:

1. A class that implements an interface must implement all its methods.


2. A class can implement multiple interfaces.
3. Use the implements keyword in the class declaration.
Default Methods (Java 8 and later):

1. Interfaces can contain default methods, which have a default implementation.


2. Default methods can be overridden in the implementing class.
Static Methods (Java 8 and later):
1. Interfaces can contain static methods. These methods belong to the interface class and cannot be
overridden in the implementing class.

Functional Interfaces (Java 8 and later):

1. An interface with exactly one abstract method is called a functional interface.


2. Can be used with lambda expressions.
Example Application: Simple Payment System

Step 1: Define the Interface

public interface Payment {

void processPayment(double amount);

default void showTransactionDetails() {

System.out.println("Transaction details not available.");

Step 2: Implement the Interface

public class CreditCardPayment implements Payment {

private String cardNumber;

private String cardHolderName;

public CreditCardPayment(String cardNumber, String cardHolderName) {

this.cardNumber = cardNumber;

this.cardHolderName = cardHolderName;

@Override

public void processPayment(double amount) {

System.out.println("Processing credit card payment of $" + amount);

// Additional logic for processing credit card payment

@Override

public void showTransactionDetails() {

System.out.println("Credit card transaction details:");

System.out.println("Card Number: " + cardNumber);

System.out.println("Card Holder: " + cardHolderName);

public class PayPalPayment implements Payment {

private String email;

public PayPalPayment(String email) {


this.email = email;

@Override

public void processPayment(double amount) {

System.out.println("Processing PayPal payment of $" + amount);

// Additional logic for processing PayPal payment

// No need to override showTransactionDetails, using default implementation

Step 3: Use the Interface

public class PaymentSystem {

public static void main(String[] args) {

Payment creditCardPayment = new CreditCardPayment("1234-5678-9876-5432", "John Doe");

Payment payPalPayment = new PayPalPayment("[email protected]");

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

Include getters/ setters.


Include a 6 argument constructor, public PublicAircraft(String aircraftName,String source,String destination,Boolean
checkinbeforetwohours,int noOfKgsallowed,float additionalFee/kg)
Include the methods displayDetails()

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

Include getters/ setters.


Include a 6 argument constructor, public PrivateAircraft(String aircraftName, String source, String destination, Boolean
checkinbeforetwohours, String pilotPreference , String purpose )
Include the methods displayDetails()

Create an AircraftMain class to test the classes defined above.


Input Format
Name of the Aircraft in the first line
Source and Destination in second and third line respectively
Aircraft type code in the fourth line (1 for Public aircraft, 2 for Private Aircraft)
If flight type is public, the next two lines should have the Number of kgs allowed per person and the additional fee
charged for extra baggage per Kg
If flight type is private, the next two lines should have the pilot name and purpose of the flight
Output Format
For public aircraft, print Aircraft Type, Aircraft Name, Source, Destination, Check-in before two hours, Number of kgs
allowed per person and Additional fee charged for extra baggage per Kg
For private aircraft, Aircraft Type, Aircraft Name, Source, Destination, Check-in before two hours, Pilot Name, Purpose
Sample Input Sample Output
Jet Airways Aircraft Type : Public Aircraft
Bangalore Aircraft Name : Jet Airways
Chennai Source : Bangalore
1 Destination : Chennai
15 Check in before two hours : Yes
750 Number of kgs allowed per person : 15
Additional fee charged for extra baggage per Kg : 750.0
3) You are in an Online shopping portal. It has two types of members, Basic and Premium. Their relationship is
shown in the inheritance diagram.

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.

Create data members and method as mentioned below.


WorkerDetail
employee code and basic salary as integer
name as string
methods to display above details and to calculate HRA(60% of basic salary)

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

Create a Main class to test above classes based on below conditions.


Minimum attendance percentage required to attend exam is 75
Teaching staff new salary will be calculated based on their result percentage (i.e.if result percentage is 87, increment will
be 8.7%)
Non teaching staff new salary will be calculated based on their experience (i.e.if experience is 2 years, the increment will
be 2%)
Input Format
Person code (1 for student, 2 for Teaching Staff, 3 for Nonteaching staff)
Name
Year of birth
Next 2 or 3 lines are based on below conditions
Department and Attendance percentage if Person code is 1
Subject, Result percentage and salary if Person code is 2
Lab Name, Experience and Salary if Person code is 3
Sample Input Sample Output
1 Name : Kumar
Kumar BirthYear : 1986
1986 Department : MCA
MCA Eligible : Yes
85
6) GST Calculation
Let's go for simple manipulation along with super class. This will be needed in our application as some class share
common attributes so they can be grouped as child classes of some super class.
To try this let's create a parent class Event with following attributes,
Then create child class Exhibition that extends Event with the following attribute,

And create another child class StageEvent that extends Event with the following attribute,

Add suitable constructor and getters/setters for the classes.


Get starting and ending date of the event from user and calculate the total cost for the event. Then calculate GST for the
event according to the event type.
GST is 5% for Exhibition and 15% for StageEvent.
Input Format
First line of the input consists of an integer
Second ,third and fourth line of the input consists of string
Fifth line of the input consists of a double value.
Next two lines of the input consists of starting and ending date of the event.( Refer sample input for the exact format)
Sample Input Sample Input
1 1
Science exhibition Movie review fest
Exciting experiments Awards for all reviewer
Fair Award function
John Sharma
10000.00 3000.00
10 250
10/10/2017 14/11/2007
12/10/2017 29/11/2007
Sample Output Sample Output
1000.0 2250.0
7) Create an interface ShapeCalculator with the following method
void calc(int n)
Create two classes Square and Circle that implement the interface and implement the method in it.
Calculate the area and perimeter of both square and circle.
Input Format
The input contains one integer which is taken as the side of the square as well as the radius of the circle.
Output Format
The output must contain the area and perimeter of each of the shapes. It must be displayed in two lines where the first
line consists of the area and perimeter of the square separated by a space and the second line has the details of the circle in
a similar format.
Details of the square must be calculated in integer type whereas for circle the calculations must be of double type
Sample Input
8
Sample Output
64 32
200.96 50.24
8) write a program to count a minimum number of front moves to sort an array.
Note: Create an interface and declare a method, the class should implement the interface.
Input Format
Input to get the size of array N in the first line, followed by N elements separated by single space in the second line.
Note: The elements must be the first N natural numbers jumbled.
Output Format
Display the output as shown in the sample output.
Constraints
N- integer type(Natural numbers)
Sample Input Sample Input
5 7
23145 5632417
Sample Output Sample Output
1 4

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

You might also like