0% found this document useful (0 votes)
34 views

Model Questions Solutions OOP Java IA 2

Uploaded by

jeonjk.7.seven
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Model Questions Solutions OOP Java IA 2

Uploaded by

jeonjk.7.seven
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Model questions for OOP with Java (IA_2)

1. Explain Method Overloading with suitable example and code snippet.


Solution: Method overloading allows multiple methods in the same class with the same name but different
parameters. Method overloading increases the readability of the program. In this example, we have created two
methods, first add() method performs addition of two integer type numbers and second add method performs
addition of two double type numbers.

Code snippet/ syntax:

public int add(int a, int b) {


return a + b;
}

public double add(double a, double b) {


return a + b;
}

- Full working code example:


public class MethodOverloadingExample {

// Method to add two integers


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

// Method to add two doubles


public double add(double a, double b) {
return a + b;
}

public static void main(String[] args) {


MethodOverloadingExample example = new MethodOverloadingExample();

// Call add() with integers


int sumInt = example.add(5, 10);
System.out.println("Sum of integers: " + sumInt);

// Call add() with doubles


double sumDouble = example.add(2.5, 3.5);
System.out.println("Sum of doubles: " + sumDouble);
}
}

Output:
Sum of integers: 8
Sum of doubles: 6.0

2. Illustrate the difference between the access modifiers – Private, Public and Protected through a
suitable example and code snippet.
Solution: Access Modifiers
- Private: Only accessible within the same class.
- Protected: Accessible within the same package and subclasses.
- Public: Accessible from any class.
- Code Snippet:
class AccessModifiersExample {
private int privateVariable; // Accessible only within this class
protected int protectedVariable; // Accessible within the package and subclasses
public int publicVariable; // Accessible from everywhere

// Public method to set the private variable


public void setPrivateVariable(int privateValue) {
privateVariable = privateValue;
}

// Public method to access private variable


public int getPrivateVariable() {
return privateVariable;
}

Full working code:

class AccessModifiersExample {
private int privateVariable; // Accessible only within this class
protected int protectedVariable; // Accessible directly within the same package
public int publicVariable; // Accessible from everywhere

// Public method to set the private variable


public void setPrivateVariable(int privateValue) {
privateVariable = privateValue;
}

// Public method to access private variable


public int getPrivateVariable() {
return privateVariable;
}
}

public class TestAccessModifiers {


public static void main(String[] args) {
AccessModifiersExample example = new AccessModifiersExample();

// Directly set public variable


example.publicVariable = 30;

// Directly set protected variable (valid as we are in the same package)


example.protectedVariable = 20;

// Set and access private variable via public methods


example.setPrivateVariable(10);
System.out.println("Private Variable: " + example.getPrivateVariable());

// Access and display protected variable


System.out.println("Protected Variable: " + example.protectedVariable);

// Access and display public variable


System.out.println("Public Variable: " + example.publicVariable);
}
}
Output:
Private Variable: 10
Protected Variable: 20
Public Variable: 30

3. Illustrate Recursion for the following with int n1 as input: a) Factorial of n1 b) Sum of all Numbers
upto n1.
Solution:

import java.util.Scanner;

public class RecursionExample {

// (a) Recursive method to calculate factorial


public static int factorial(int n1) {
if (n1 == 0) { // Base case
return 1;
}
return n * factorial(n1 - 1);
}

// (b) Recursive method to calculate the sum of all numbers up to n1


public static int sumUpTo(int n1) {
if (n1 == 0) { // Base case
return 0;
}
return n1 + sumUpTo(n1 - 1);
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Input from user


System.out.print("Enter a positive integer (n1): ");
int n1 = scanner.nextInt();

if (n1 < 0) {
System.out.println("Please enter a positive integer.");
} else {
// Calculate and display results
int factorialResult = factorial(n1);
int sumResult = sumUpTo(n1);

System.out.println("Factorial of " + n1 + " is: " + factorialResult);


System.out.println("Sum of all numbers up to " + n1 + " is: " + sumResult);
}
scanner.close();
}
}

4. Create a class called StudentResume. Within this, create 2 nested classes CollegeAddress,
HomeAddress. Write constructor methods to print address containing location, city, pincode, state. In
public class TestStudentResume, create objects of the outer class and the two inner classes. Depending
on user input, print the resume and the respective address.
Solution:
import java.util.Scanner;

class StudentResume {

// Outer class constructor


private String name;
private String email;

public StudentResume(String name, String email) {


this.name = name;
this.email = email;
}

// Nested class CollegeAddress


class CollegeAddress {
private String location;
private String city;
private String pincode;
private String state;

public CollegeAddress(String location, String city, String pincode, String state) {


this.location = location;
this.city = city;
this.pincode = pincode;
this.state = state;
}

public void printCollegeAddress() {


System.out.println("College Address:");
System.out.println("Location: " + location);
System.out.println("City: " + city);
System.out.println("Pincode: " + pincode);
System.out.println("State: " + state);
}
}

// Nested class HomeAddress


class HomeAddress {
private String location;
private String city;
private String pincode;
private String state;

public HomeAddress(String location, String city, String pincode, String state) {


this.location = location;
this.city = city;
this.pincode = pincode;
this.state = state;
}

public void printHomeAddress() {


System.out.println("Home Address:");
System.out.println("Location: " + location);
System.out.println("City: " + city);
System.out.println("Pincode: " + pincode);
System.out.println("State: " + state);
}
}

public void printResume() {


System.out.println("\nStudent Resume:");
System.out.println("Name: " + name);
System.out.println("Email: " + email);
}
}

public class TestStudentResume {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Getting input from user


System.out.print("Enter student's name: ");
String name = scanner.nextLine();

System.out.print("Enter student's email: ");


String email = scanner.nextLine();

StudentResume student = new StudentResume(name, email);

// Creating CollegeAddress and HomeAddress objects


System.out.print("Enter college location: ");
String collegeLocation = scanner.nextLine();
System.out.print("Enter college city: ");
String collegeCity = scanner.nextLine();
System.out.print("Enter college pincode: ");
String collegePincode = scanner.nextLine();
System.out.print("Enter college state: ");
String collegeState = scanner.nextLine();

StudentResume.CollegeAddress collegeAddress = student.new CollegeAddress(collegeLocation,


collegeCity, collegePincode, collegeState);

System.out.print("Enter home location: ");


String homeLocation = scanner.nextLine();
System.out.print("Enter home city: ");
String homeCity = scanner.nextLine();
System.out.print("Enter home pincode: ");
String homePincode = scanner.nextLine();
System.out.print("Enter home state: ");
String homeState = scanner.nextLine();

StudentResume.HomeAddress homeAddress = student.new HomeAddress(homeLocation, homeCity,


homePincode, homeState);

// Printing resume and addresses based on user input


student.printResume();

System.out.println("\nDo you want to print College or Home Address? (Enter 'college' or 'home')");
String addressChoice = scanner.nextLine().toLowerCase();

if (addressChoice.equals("college")) {
collegeAddress.printCollegeAddress();
} else if (addressChoice.equals("home")) {
homeAddress.printHomeAddress();
} else {
System.out.println("Invalid choice!");
}

scanner.close();
}
}

5. Explain usage of static keyword with example.


Solution:
The `static` keyword in Java is used to indicate that a member (variable, method, or nested class) belongs to
the class rather than to any specific instance of the class. Here's a detailed explanation with examples:

(a) Static Variables:


- A `static` variable is shared among all instances of the class. It is stored in the class's memory rather than in
each object.
- Useful for maintaining a common property or count.

Example:

class Counter {
static int count = 0; // Static variable shared among all instances

Counter() {
count++; // Increment count for each object creation
}

void displayCount() {
System.out.println("Count: " + count);
}
}

public class TestStaticVariable {


public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();

c1.displayCount(); // Count: 3
c2.displayCount(); // Count: 3
c3.displayCount(); // Count: 3
}
}

(b) Static Methods:


- A `static` method belongs to the class, not to any object.
- It can be called without creating an instance of the class.
- A `static` method cannot access instance variables or methods directly because it does not operate on an
object.

Example:

class MathOperations {
// Static method for addition
static int add(int a, int b) {
return a + b;
}
}

public class TestStaticMethod {


public static void main(String[] args) {
int result = MathOperations.add(10, 20); // Directly calling static method
System.out.println("Result: " + result); // Result: 30
}
}

(c) Static Blocks:


- A `static` block is used to initialize static variables or perform setup operations.
- It is executed when the class is loaded into memory, before any objects are created or static methods are
called.

Example:
class Config {
static String appName;
static int version;

// Static block to initialize static variables


static {
appName = "MyApp";
version = 1;
System.out.println("Static block executed!");
}
}

public class TestStaticBlock {


public static void main(String[] args) {
System.out.println("App Name: " + Config.appName);
System.out.println("Version: " + Config.version);
}
}

Output:
Static block executed!
App Name: MyApp
Version: 1

(d) Static Nested Classes:


- A nested class declared `static` does not need a reference to the outer class.
- Useful for grouping classes logically and reducing clutter.

Example:
class OuterClass {
static class NestedClass {
void displayMessage() {
System.out.println("Hello from Static Nested Class!");
}
}
}

public class TestStaticNestedClass {


public static void main(String[] args) {
OuterClass.NestedClass nested = new OuterClass.NestedClass(); // No instance of OuterClass needed
nested.displayMessage();
}
}

Key Points to Remember:


1. Static Variable: Shared across all objects; changes reflect in all instances.
2. Static Method: Cannot access non-static (instance) members directly.
3. Static Block: Runs once when the class is loaded.
4. Static Nested Class: Independent of the instance of the enclosing class.

6. Illustrate Method Overloading with suitable example to demonstrate No parameter, Passing of two
parameters, Passing an object.
Solution:
class Calculator {

// 1. Method with no parameters


void add() {
System.out.println("No parameters provided for addition.");
}

// 2. Method with two int parameters


void add(int a, int b) {
int sum = a + b;
System.out.println("Sum of " + a + " and " + b + " is: " + sum);
}

// 3. Method with an object parameter (int[] as object)


void add(int[] numbers) {
if (numbers.length < 2) { // Ensure at least two numbers are present
System.out.println("Insufficient numbers provided.");
return;
}
int sum = 0;
for (int num : numbers) { // Calculate the sum of all numbers in the array
sum += num;
}
System.out.println("Sum using object (array): " + sum);
}
}

public class MethodOverloadingDemo {


public static void main(String[] args) {
Calculator calc = new Calculator();

// Call method with no parameters


calc.add();

// Call method with two int parameters


calc.add(10, 20);

// Call method with an object parameter (int[] array)


int[] numbers = {15, 25, 35};
calc.add(numbers); // Passing an array object
}
}

Output:
No parameters provided for addition.
Sum of 10 and 20 is: 30
Sum using object (array): 75

7. Create class InternalMarks, created two NestedClasses IA and Lab. Within IA class, create method
showmarks(int n1). If student has got marks 15, 20, 18 in three IAs, only best two should be considered.
Write a working program. (you may get this question in IA like this, but should be interpreted as the
corrected one)

CORRECTED QUESTION SHOULD BE:


Create a class InternalMarks with two nested classes: IA and Lab. Within the IA class, create a method
showMarks(int n1, int n2, int n3) that takes three integers as arguments. If a student has scores of 15,
20, and 18 in three internal assessments, calculate the total of the best two marks.
Write a working program.

Solution:

import java.util.Scanner; // Import Scanner for user input

class InternalMarks {

// Nested Class IA
class IA {
void showMarks(int n1, int n2, int n3) {
// Find the lowest mark among the three using Math.min
int lowest = Math.min(n1, Math.min(n2, n3));

// Calculate the total of the best two marks by subtracting the lowest mark
int totalBestTwo = (n1 + n2 + n3) - lowest;

// Display the marks and the total of the best two


System.out.println("Marks in three IAs: " + n1 + ", " + n2 + ", " + n3);
System.out.println("Best two marks total: " + totalBestTwo);
}
}

// Nested Class Lab


class Lab {
void showLabDetails() {
System.out.println("Lab marks functionality can be added here.");
}
}
}

public class TestInternalMarks {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // Create a Scanner object

// Create an object of the outer class


InternalMarks internalMarks = new InternalMarks();

// Create an object of the nested IA class


InternalMarks.IA ia = internalMarks.new IA();

// Prompt user for IA marks


System.out.print("Enter marks for IA1: ");
int ia1 = scanner.nextInt();

System.out.print("Enter marks for IA2: ");


int ia2 = scanner.nextInt();

System.out.print("Enter marks for IA3: ");


int ia3 = scanner.nextInt();

// Pass marks to the showMarks method


ia.showMarks(ia1, ia2, ia3);

// Create and use the Lab class object


InternalMarks.Lab lab = internalMarks.new Lab();
lab.showLabDetails(); // Placeholder for Lab functionality

scanner.close(); // Close the scanner


}
}

Output:
Marks in three IAs: 15, 20, 18
Best two marks total: 38
Lab marks functionality can be added here.

8. Create a class Box having attributes length, width and height. A small box has dimensions (3,4,5). A
large box has dimensions (10,20,30). Every box has 6 faces. Declare this as a static attribute. Write
methods to compute the volume of SmallBox b1 and LargeBox b2.

Solution:
class Box {
// Attributes for dimensions of the box
private int length, width, height;

// Static attribute representing the number of faces for every box


static final int numberOfFaces = 6;

// Constructor to initialize the dimensions of the box


public Box(int length, int width, int height) {
this.length = length;
this.width = width;
this.height = height;
}

// Method to compute the volume of the box


public int computeVolume() {
return length * width * height;
}

// Method to display the details of the box


public void displayBoxDetails(String boxName) {
System.out.println(boxName + " Dimensions: " +
"Length = " + length + ", Width = " + width + ", Height = " + height);
System.out.println("Number of Faces: " + numberOfFaces);
System.out.println("Volume: " + computeVolume());
}
}

public class TestBox {


public static void main(String[] args) {
// Create SmallBox with dimensions 3, 4, 5
Box b1 = new Box(3, 4, 5);

// Create LargeBox with dimensions 10, 20, 30


Box b2 = new Box(10, 20, 30);

// Display details and compute volumes for both boxes


b1.displayBoxDetails("SmallBox");
System.out.println(); // Spacer for better readability
b2.displayBoxDetails("LargeBox");
}
}

Output:
SmallBox Dimensions: Length = 3, Width = 4, Height = 5
Number of Faces: 6
Volume: 60

LargeBox Dimensions: Length = 10, Width = 20, Height = 30


Number of Faces: 6
Volume: 6000

9. Explain Method Overriding with suitable example and code snippet.


Solution:
Method overriding in Java occurs when a subclass (child class) provides a specific implementation of a
method that is already defined in its superclass (parent class). The method in the subclass must have the same
name, return type, and parameters as the method in the parent class.

Key Points:

1. Inheritance: Overriding requires a subclass to inherit from a superclass.


2. @Override Annotation: It's a good practice to use the @Override annotation to indicate that a method
is overridden.
3. Runtime Polymorphism: Method overriding is an example of runtime polymorphism. The method to
be executed is determined at runtime, based on the object's type.
4. Rules:
o The method in the subclass must have the same signature as the method in the superclass.
o The method in the subclass cannot have a stricter access modifier than the method in the
superclass.
o If the method in the superclass is final, it cannot be overridden.

Code snippet/ syntax:

public class TestOverriding {

public static void main(String[] args) {

// Superclass reference pointing to a Subclass object

Superclass obj = new Subclass();

// Calls the overridden method

obj.methodName(); // Output: Method in Subclass

Complete working code:

// Superclass

class Animal {
// Method to be overridden

public void sound() {

System.out.println("Animals make sounds");

// Subclass

class Dog extends Animal {

// Overriding the sound() method

@Override

public void sound() {

System.out.println("Dogs bark");

public class TestOverriding {

public static void main(String[] args) {

// Reference of superclass pointing to an object of subclass

Animal myDog = new Dog();

// Call the overridden method

myDog.sound(); // Runtime polymorphism

Output:

Dogs bark
10. When is “final” used for variables? When is “final” used for methods? Why? Write a suitable code
snippet.
Solution:

When to Use final:

1. Final Variables:
o To define constants like PI, MAX_VALUE, etc.
o To prevent accidental modification of critical data.
2. Final Methods:
o To ensure the base class method's functionality is preserved and not altered by subclasses.

Why Use final?


1. Final Variables (Immutability):
o Prevents reassignment of values, ensuring data integrity.
o Useful for defining constants (e.g., PI or MAX_VALUE) that should remain unchanged
throughout the program.
o Enhances readability and makes it clear that the value is a constant.
Example:
final int MAX_SPEED = 120; // This value cannot be changed later.
2. Final Methods (Security):
o Prevents overriding of critical methods in subclasses, preserving the original behavior of the
method.
o Ensures the parent class’s implementation cannot be altered maliciously or accidentally by
derived classes.
o Ideal for methods that are part of the core functionality or API.
Example:
public final void displayMessage() {
System.out.println("Critical operation that should not be overridden.");
}

Code snippet:
class ParentClass {
final double PI = 3.14159; // Final variable (constant)

public final void displayMessage() { // Final method


System.out.println("This is a final method and cannot be overridden.");
}
}

class ChildClass extends ParentClass {


// PI is inherited as a final variable; cannot be modified
// Example: PI = 3.14; // This will cause a compilation error

// Uncommenting this will cause a compilation error


// @Override
// public void displayMessage() {
// System.out.println("Cannot override final method.");
// }
}
11. Write a Java program to show multi-level inheritance using the classes SMVITM, CSE,
Batch4MW23CS. 50 students have USNs in sequence. 4 new students do not have any roll-number
allocated. Use suitable constructor and methods to write a working program to print the USNs of all the
students.
Solution:
// Base class
class SMVITM {
protected String collegeName = "SMVITM"; // College name
protected int totalStudents = 50; // Total students with allocated USNs

public void printCollegeDetails() {


System.out.println("College: " + collegeName);
System.out.println("Total Students with USNs: " + totalStudents);
}
}

// Intermediate class
class CSE extends SMVITM {
protected String departmentName = "CSE"; // Department name

public void printDepartmentDetails() {


System.out.println("Department: " + departmentName);
}
}

// Derived class
class Batch4MW23CS extends CSE {
private String[] usns = new String[54]; // Array to hold USNs for 50 students + 4 unallocated

// Constructor to initialize USNs


public Batch4MW23CS() {
// Assign USNs for the first 50 students
for (int i = 0; i < 50; i++) {
usns[i] = "4MW23CS" + String.format("%03d", i + 1); // Generate USNs in sequence
}
// Indicate no USN for the remaining 4 students
for (int i = 50; i < usns.length; i++) {
usns[i] = "No USN Allocated"; // Placeholder for unallocated students
}
}

// Method to print all USNs


public void printUSNs() {
System.out.println("USNs of students:");
for (int i = 0; i < usns.length; i++) {
System.out.println("Student " + (i + 1) + ": " + usns[i]);
}
}
}

// Main class
public class MultiLevelInheritanceDemo {
public static void main(String[] args) {
// Create an object of the most derived class
Batch4MW23CS batch = new Batch4MW23CS();

// Print details from all levels of inheritance


batch.printCollegeDetails();
batch.printDepartmentDetails();
batch.printUSNs();
}
}

Output:
College: SMVITM
Total Students with USNs: 50
Department: CSE
USNs of students:
Student 1: 4MW23CS001
Student 2: 4MW23CS002
...
Student 50: 4MW23CS050
Student 51: No USN Allocated
Student 52: No USN Allocated
Student 53: No USN Allocated
Student 54: No USN Allocated

12. Illustrate the use of “super” keyword using suitable example. Dog is a child class of Animal.
getColour() in Animal class gives black, getColour() in Dog class gives white. Write Java code using
“super”.
Solution:
// Parent class
class Animal {
// Method in the parent class
public String getColour() {
return "Black";
}
}

// Child class
class Dog extends Animal {
// Overriding the method in the child class
@Override
public String getColour() {
return "White";
}

// Method to show the use of 'super'


public void displayColours() {
// Accessing the overridden method in the child class
System.out.println("Dog's Colour: " + getColour());

// Accessing the method in the parent class using 'super'


System.out.println("Animal's Colour: " + super.getColour());
}
}

// Main class
public class SuperKeywordDemo {
public static void main(String[] args) {
// Create an object of the Dog class
Dog dog = new Dog();

// Display colours using the 'displayColours' method


dog.displayColours();
}
}

Output:
Dog's Colour: White
Animal's Colour: Black

13. Explain object class briefly.

Solution:

Object Class in Java


The Object class is the root class of the Java class hierarchy, and every class in Java inherits from it either
directly or indirectly.

Key Features:
1. Inheritance:
o Every Java class implicitly extends Object.
o Example:
class MyClass { } // Implicitly extends Object
2. Core Methods:
o toString(): Returns a string representation of the object.
o equals(Object obj): Compares objects for equality.
o hashCode(): Provides a hash code for the object.
o getClass(): Returns the runtime class of the object.
o wait(), notify(), notifyAll(): Used in thread synchronization.

Example:
toString() and equals():

class MyClass {
int value;

MyClass(int value) {
this.value = value;
}

@Override
public String toString() {
return "Value: " + value;
}

@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
MyClass other = (MyClass) obj;
return value == other.value;
}
}

public class TestObject {


public static void main(String[] args) {
MyClass obj1 = new MyClass(10);
MyClass obj2 = new MyClass(10);
System.out.println(obj1); // Output: Value: 10
System.out.println(obj1.equals(obj2)); // Output: true
}
}

14. A car showroom needs a billing system for different car models. Write a program illustrating a muti-
level inheritance with the following classes. Vehicle, 4Wheeler, MarutiSuzuki, Alto, Celerio, Swift.
Only the Swift model has method automaticDrive(). Other models have method manualDrive() only.
Create a simple billing system for the showroom.
Solution:
import java.util.Scanner;

// Base class
class Vehicle {
public void displayType() {
System.out.println("This is a vehicle.");
}
}

// Intermediate class: 4-Wheeler


class FourWheeler extends Vehicle {
public void displayCategory() {
System.out.println("This is a 4-Wheeler.");
}
}

// Intermediate class: MarutiSuzuki


class MarutiSuzuki extends FourWheeler {
public void displayBrand() {
System.out.println("This is a Maruti Suzuki car.");
}
}

// Specific model: Alto


class Alto extends MarutiSuzuki {
public void manualDrive() {
System.out.println("Alto supports manual driving.");
}

public double getPrice() {


return 500000; // Price of Alto in INR
}
}

// Specific model: Celerio


class Celerio extends MarutiSuzuki {
public void manualDrive() {
System.out.println("Celerio supports manual driving.");
}

public double getPrice() {


return 650000; // Price of Celerio in INR
}
}

// Specific model: Swift


class Swift extends MarutiSuzuki {
public void automaticDrive() {
System.out.println("Swift supports automatic driving.");
}

public double getPrice() {


return 850000; // Price of Swift in INR
}
}

// Main class for billing system


public class CarShowroom {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Welcome to the Car Showroom!");


System.out.println("Available Models: 1. Alto 2. Celerio 3. Swift");
System.out.print("Enter the model number you want to purchase: ");
int choice = scanner.nextInt();

double price = 0;
switch (choice) {
case 1:
Alto alto = new Alto();
alto.displayType();
alto.displayCategory();
alto.displayBrand();
alto.manualDrive();
price = alto.getPrice();
break;

case 2:
Celerio celerio = new Celerio();
celerio.displayType();
celerio.displayCategory();
celerio.displayBrand();
celerio.manualDrive();
price = celerio.getPrice();
break;

case 3:
Swift swift = new Swift();
swift.displayType();
swift.displayCategory();
swift.displayBrand();
swift.automaticDrive();
price = swift.getPrice();
break;

default:
System.out.println("Invalid choice! Please select a valid model.");
return;
}

System.out.print("Enter the quantity of cars you want to purchase: ");


int quantity = scanner.nextInt();
double total = price * quantity;

System.out.println("\n--- Invoice ---");


System.out.println("Model Price: " + price + " INR");
System.out.println("Quantity: " + quantity);
System.out.println("Total Amount: " + total + " INR");
System.out.println("Thank you for your purchase!");
}
}

Output:
Welcome to the Car Showroom!
Available Models: 1. Alto 2. Celerio 3. Swift
Enter the model number you want to purchase: 2
This is a vehicle.
This is a 4-Wheeler.
This is a Maruti Suzuki car.
Celerio supports manual driving.
Enter the quantity of cars you want to purchase: 2

--- Invoice ---


Model Price: 650000.0 INR
Quantity: 2
Total Amount: 1300000.0 INR
Thank you for your purchase!

15. Write a Java program having class SmartPhone inherited from parent class ElectronicDevice and
from interfaces “GPS”, “Radio” and “Bluetooth”. Declare a method in each interface and implement
them in the child class. In public class TestSmartPhone, print the features of 2 different models.
Solution:

// Parent class
class ElectronicDevice {
private String brand;
public ElectronicDevice(String brand) {
this.brand = brand;
}

public String getBrand() {


return brand;
}

public void powerOn() {


System.out.println(brand + " device is powered on.");
}

public void powerOff() {


System.out.println(brand + " device is powered off.");
}
}

// GPS Interface
interface GPS {
void navigate();
}

// Radio Interface
interface Radio {
void playRadio();
}

// Bluetooth Interface
interface Bluetooth {
void connectBluetooth();
}

// Child class implementing multiple interfaces


class SmartPhone extends ElectronicDevice implements GPS, Radio, Bluetooth {
private String model;

public SmartPhone(String brand, String model) {


super(brand);
this.model = model;
}

public String getModel() {


return model;
}

@Override
public void navigate() {
System.out.println(model + " has GPS navigation feature.");
}

@Override
public void playRadio() {
System.out.println(model + " can play FM radio.");
}

@Override
public void connectBluetooth() {
System.out.println(model + " supports Bluetooth connectivity.");
}

public void showFeatures() {


System.out.println("Features of " + getBrand() + " " + model + ":");
powerOn();
navigate();
playRadio();
connectBluetooth();
powerOff();
System.out.println();
}
}

// Main class
public class TestSmartPhone {
public static void main(String[] args) {
// Creating two different smartphone models
SmartPhone phone1 = new SmartPhone("BrandA", "ModelX");
SmartPhone phone2 = new SmartPhone("BrandB", "ModelY");

// Printing features of each smartphone


phone1.showFeatures();
phone2.showFeatures();
}
}

Output:
Features of BrandA ModelX:
BrandA device is powered on.
ModelX has GPS navigation feature.
ModelX can play FM radio.
ModelX supports Bluetooth connectivity.
BrandA device is powered off.

Features of BrandB ModelY:


BrandB device is powered on.
ModelY has GPS navigation feature.
ModelY can play FM radio.
ModelY supports Bluetooth connectivity.
BrandB device is powered off.

16. Federal Express is a courier service having different rates for shipping -small boxes, big boxes, fragile
boxes. Federal Express also wants to add GST to the pricing through an interface “Taxable” Write a Java
code to illustrate using inheritance of class and interface.
Solution:
// Interface for Taxable
interface Taxable {
double GST_RATE = 0.18; // 18% GST

double calculateGST(double basePrice);


}

// Parent class: CourierService


class CourierService {
private String boxType;
private double basePrice;

public CourierService(String boxType, double basePrice) {


this.boxType = boxType;
this.basePrice = basePrice;
}

public String getBoxType() {


return boxType;
}

public double getBasePrice() {


return basePrice;
}

public void displayInfo() {


System.out.println("Box Type: " + boxType);
System.out.println("Base Price: Rs." + basePrice);
}
}

// Child class: SmallBox


class SmallBox extends CourierService implements Taxable {
public SmallBox(double basePrice) {
super("Small Box", basePrice);
}

@Override
public double calculateGST(double basePrice) {
return basePrice * GST_RATE;
}
}

// Child class: BigBox


class BigBox extends CourierService implements Taxable {
public BigBox(double basePrice) {
super("Big Box", basePrice);
}

@Override
public double calculateGST(double basePrice) {
return basePrice * GST_RATE;
}
}
// Child class: FragileBox
class FragileBox extends CourierService implements Taxable {
public FragileBox(double basePrice) {
super("Fragile Box", basePrice);
}

@Override
public double calculateGST(double basePrice) {
return basePrice * GST_RATE;
}
}

// Main class
public class FederalExpress {
public static void main(String[] args) {
// Create instances of different box types
SmallBox smallBox = new SmallBox(200);
BigBox bigBox = new BigBox(500);
FragileBox fragileBox = new FragileBox(1000);

// Display details and GST for SmallBox


System.out.println("Small Box:");
smallBox.displayInfo();
System.out.println("GST: Rs." + smallBox.calculateGST(smallBox.getBasePrice()));
System.out.println("Total Price: Rs." + (smallBox.getBasePrice() +
smallBox.calculateGST(smallBox.getBasePrice())));
System.out.println();

// Display details and GST for BigBox


System.out.println("Big Box:");
bigBox.displayInfo();
System.out.println("GST: Rs." + bigBox.calculateGST(bigBox.getBasePrice()));
System.out.println("Total Price: Rs." + (bigBox.getBasePrice() +
bigBox.calculateGST(bigBox.getBasePrice())));
System.out.println();

// Display details and GST for FragileBox


System.out.println("Fragile Box:");
fragileBox.displayInfo();
System.out.println("GST: Rs." + fragileBox.calculateGST(fragileBox.getBasePrice()));
System.out.println("Total Price: Rs." + (fragileBox.getBasePrice() +
fragileBox.calculateGST(fragileBox.getBasePrice())));
}
}
Output:
Small Box:
Box Type: Small Box
Base Price: Rs.200.0
GST: Rs.36.0
Total Price: Rs.236.0

Big Box:
Box Type: Big Box
Base Price: Rs.500.0
GST: Rs.90.0
Total Price: Rs.590.0

Fragile Box:
Box Type: Fragile Box
Base Price: Rs.1000.0
GST: Rs.180.0
Total Price: Rs.1180.0

You might also like