0% found this document useful (0 votes)
11 views13 pages

Inheritance Iamneao Unit 1

The document contains multiple-choice questions and coding problems related to Java inheritance and method overriding. It covers topics such as class inheritance, method access levels, and practical coding scenarios involving classes like Product, Subscription, and Pizza. The document also includes example code solutions for various programming problems involving inheritance in Java.

Uploaded by

srijapapai04
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)
11 views13 pages

Inheritance Iamneao Unit 1

The document contains multiple-choice questions and coding problems related to Java inheritance and method overriding. It covers topics such as class inheritance, method access levels, and practical coding scenarios involving classes like Product, Subscription, and Pizza. The document also includes example code solutions for various programming problems involving inheritance in Java.

Uploaded by

srijapapai04
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/ 13

CMREC_Java_Unit 1_MCQ_Inheritance_Overriding

Q1.Which of these is the correct way of inheriting class A by class B?

1. class B + class A {}

2. class B inherits class A {}

3. class B extends A {}

4. class B extends class A {}

ans:
class B extends A {}

Q2.A class member declared protected becomes a member of a subclass of which type?

1. public member

2. private member

3. protected member

4. static member

ans:
private member

Explanation: A class member declared protected becomes a private member of subclass.

Q3.What will be the output of the following program?

class A {

public int i;

public int j;

A()

i = 1;

j = 2;

class B extends A {

int a;
B()

super();

class super_use {

public static void main(String args[]) {

B obj = new B();

System.out.println(obj.i + " " + obj.j);

Ans:

12

Explanation: super() function is used to call the super/parent class constructor.

In the above example super() in Class B, call the A’s class constructor so I in initialized with 1 and j is
initialized with 2

4.What will be the output of the following program?

class A {

public int i;

private int j;

class B extends A {

void display() {

super.j = super.i + 1;

System.out.println(super.i + " " + super.j);

class inheritance {

public static void main(String args[]) {


B obj = new B();

obj.i=1;

obj.j=2;

obj.display();

Ans: compile time error

Explanation:

Explanation: super keyword is used to access super/parent class variables.


(except Private members)

by using super keyword we can access A’s class member such as i and j .but here in above program j
is declared as private .So by using super.j we cant deal with j in ClassA

Q5.Consider the hierarchy of classes shown below.

Which represent valid class headers that would be found in this hierarchy?

1. public class ScriptedShow extends TelevisionShow {. . .

public class Comedy extends ScriptedShow {. . .

2. public class TelevisionShow extends ScriptedShow {. . .


public class ScriptedShow extends Comedy {. . .

3. public class Drama extends TelevisionShow {. . .

public class Comedy extends Drama {. . .

4 public class ScriptedShow extends RealityShow {. . .

public class RealityShow extends ScriptedShow {. . .

ans:
public class ScriptedShow extends TelevisionShow {. . .

public class Comedy extends ScriptedShow {. . .

Q6. What happens if a subclass attempts to override a private method from its superclass?
1. Compile-time Error

2. Normal method overriding occurs

3. A warning message will be displayed

4. None of the mentioned options

Ans: Compile-time Error

Q7.What will be the output of the following code snippet?


class Parent {
void show() {
System.out.println("Parent's show()");
}
}

class Child extends Parent {


void show() {
System.out.println("Child's show()");
}
}

public class Main {


public static void main(String[] args) {
Parent obj = new Child();
obj.show();
}
}
Ans: Child's show()

Explanation:upcasting and overriding concept is used in above program.

Q8 What will be the output for the following code snippet?


class A {
void display() {
System.out.println("A display()");
}
}

class B extends A {
void display() {
System.out.println("B display()");
}
}

class C extends B {
void display() {
System.out.println("C display()");
}
}

public class Main {


public static void main(String[] args) {
A obj = new C();
obj.display();
}
}
Ans:
C display()
Explanation: Same as above program explanation

Q9. Java inheritance is used


1. for code re-usability

2. to achieve runtime polymorphism

3. Both for code re-usability and to achieve runtime polymorphism

4. None of these

Ans: Both for code re-usability and to achieve runtime polymorphism


Q10.
Object-oriented inheritance models the

1. “is a kind of” relationship

2. “has a” relationship
3. “want to be” relationship

4. inheritance does not describe any kind of relationship between classes

ans:
“is a kind of” relationship

CMREC_Java_Unit 1_COD_Inheritance_Overriding

Q1.

Problem Statement
Alice is managing an online store and wants to implement a program in the pricing system for her
products. She has a base class called Product with a public double attribute price.

Additionally, she has a subclass called DiscountedProduct, which extends Product and includes a
private double attribute discountRate.
This subclass has a method called calculateSellingPrice() to determine the final selling price after
applying the discount.
Formula: Discounted Selling Price = Price * (1 - Discount Rate)

Solution:
import java.util.Scanner;

class Product {
public double price;
}

class DiscountedProduct extends Product {


private double discountRate;

public DiscountedProduct(double price, double discountRate) {


this.price = price;
this.discountRate = discountRate;
}

public double calculateSellingPrice() {


double discountedPrice = price * (1 - discountRate);
return discountedPrice;
}
}

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

double initialPrice = scanner.nextDouble();


double discountRate = scanner.nextDouble();
DiscountedProduct discountedProduct = new DiscountedProduct(initialPrice, discountRate);
double sellingPrice = discountedProduct.calculateSellingPrice();

if (sellingPrice >= 0) {
System.out.printf("Rs. %.2f%n", sellingPrice);
} else {
System.out.println("Not applicable");
}
scanner.close();
}
}

Q2: Problem Statement


Elsa subscribes to a premium service with a base monthly cost, a service tax, and an extra feature
cost. She wants to write a program that takes input for these values and calculates the total monthly
cost of Elsa's subscription.

The PremiumSubscription class inherits from the Subscription class and has a method,
calculateMonthlyCost(), to determine the total cost.

Note

Total Cost = Monthly Cost + Service Tax + Extra Feature Cost

import java.util.Scanner;

class Subscription {
public double monthlyCost;
public double serviceTax;
public double extraFeatureCost;
}

class PremiumSubscription extends Subscription {


public PremiumSubscription(double monthlyCost, double serviceTax, double extraFeatureCost) {
this.monthlyCost = monthlyCost;
this.serviceTax = serviceTax;
this.extraFeatureCost = extraFeatureCost;
}

public double calculateMonthlyCost() {


double totalCost = monthlyCost + serviceTax + extraFeatureCost;
return totalCost;
}
}

public class Main {


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

double baseMonthlyCost = scanner.nextDouble();


double serviceTax = scanner.nextDouble();
double extraFeatureCost = scanner.nextDouble();
PremiumSubscription premiumSubscription = new PremiumSubscription(baseMonthlyCost,
serviceTax, extraFeatureCost);

double totalMonthlyCost = premiumSubscription.calculateMonthlyCost();

System.out.printf("Rs. %.2f%n", totalMonthlyCost);

scanner.close();
}
}

Q3.
Problem Statement

Mary is managing a business and wants to analyze its profitability. She has a regular business model
and a seasonal one. Mary is using a program that calculates and compares the profit margins of both
models based on revenue and costs.
The program defines a base class BusinessUtility with a method for calculating the profit margin and
a derived class SeasonalBusinessUtility that overrides the margin calculation method to include an
additional seasonal adjustment.
Note

Margin = (Revenue − Cost)/Revenue * 100

Seasonal margin = (margin + 10)


Solution:
import java.util.Scanner;
import java.text.DecimalFormat;

class BusinessUtility {
public double calculateMargin(double revenue, double cost) {
double margin = ((revenue - cost) / revenue) * 100;
return margin;
}
}

class SeasonalBusinessUtility extends BusinessUtility {

public double calculateMargin(double revenue, double cost) {


double baseMargin = super.calculateMargin(revenue, cost);
double seasonalMargin = baseMargin + 10;
return seasonalMargin;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

double revenue = scanner.nextDouble();


double cost = scanner.nextDouble();
BusinessUtility business = new BusinessUtility();
SeasonalBusinessUtility seasonalBusiness = new SeasonalBusinessUtility();

double regularMargin = business.calculateMargin(revenue, cost);


double seasonalMargin = seasonalBusiness.calculateMargin(revenue, cost);

DecimalFormat df = new DecimalFormat("#.00");

System.out.println("Regular Margin: " + df.format(regularMargin) + "%");


System.out.println("Seasonal Margin: " + df.format(seasonalMargin) + "%");

if (regularMargin < 10) {


System.out.println("Business is not profitable.");
} else {
System.out.println("Business is profitable.");
}

scanner.close();
}
}

CMREC_Java_Unit 1_CY_Inheritance_Overriding

Q1.
Problem Statement
Adhi, a travel enthusiast, wishes to calculate the travel distance of his car based on its speed and fuel
capacity. He decides to create a program using single inheritance.
The Vehicle class holds attributes for speed and fuel capacity, while the Car class extends Vehicle and
includes a method to calculate travel distance.
Adhi inputs speed and fuel capacity, and the program displays the details, including the calculated
travel distance.
Note: Travel Distance = Speed * Fuel Capacity.
Solution:
import java.util.Scanner;

class Vehicle {
public double speed;
public double fuelCapacity;
}

class Car extends Vehicle {


public Car(double speed, double fuelCapacity) {
this.speed = speed;
this.fuelCapacity = fuelCapacity;
}

public double calculateTravelDistance() {


return speed * fuelCapacity;
}
}

public class Main {


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

double speed = scanner.nextDouble();


double fuelCapacity = scanner.nextDouble();

Car car = new Car(speed, fuelCapacity);

System.out.println("Speed: " + String.format("%.2f", car.speed) + " km/h");


System.out.println("Fuel Capacity: " + String.format("%.2f", car.fuelCapacity) + " liters");
System.out.println("Travel Distance: " + String.format("%.2f", car.calculateTravelDistance()) + "
km");

scanner.close();
}
}
Q2.
Problem Statement
Teena's Retail Store has implemented a Loyalty Points System to reward customers based on their
spending. The program includes two classes: Customer and PremiumCustomer.
Loyalty points for Regular Customers are calculated as one point per ten units spent, while Premium
Customers, through the overridden method in the PremiumCustomer class, receive double points.
For Regular Customers:
Loyalty points are calculated as one point for every ten units of currency spent
Loyalty Points = Amount Spent / 10
For Premium Customers:
Premium customers receive double the loyalty points compared to regular customers. That is two
points for every ten units of currency spent.
Loyalty Points = 2 * (Amount Spent / 10)
Solution:
import java.util.Scanner;

class Customer {
public int calculateLoyaltyPoints(int amountSpent) {
return amountSpent / 10;
}
}

class PremiumCustomer extends Customer {


public int calculateLoyaltyPoints(int amountSpent) {
return 2 * (amountSpent / 10);
}
}

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int amountSpent = scanner.nextInt();

String isPremium = scanner.next().toLowerCase();

Customer customer;

if (isPremium.equals("yes")) {
customer = new PremiumCustomer();
} else {
customer = new Customer();
}

int loyaltyPoints = customer.calculateLoyaltyPoints(amountSpent);

System.out.println(loyaltyPoints);
}
}
CMREC_Java_Unit 1_PAH_Inheritance_Overriding

Q1.
Problem Statement

Karthick is working on a program involving Parent and Main classes.


The Parent class contains a method named fun that takes an integer N as input and performs the
following operations:
Extract each digit from the given integer N.
Calculate the square of each digit.
Sum up the squares of all the digits.
Print the final sum.
The Main class extends the Parent class and includes the main method. The main method prompts
the user for an integer N, creates an instance of the Main class, and invokes the fun method of the
Parent class.
Solution:

import java.util.Scanner;

class Parent {
void fun(int n) {
int i, j, k = 0, sum = 0;
int a[] = new int[10];

while (n != 0) {
i = n % 10;
a[k++] = i * i;
n = n / 10;
}

for (i = 0; i < k; i++) {


sum += a[i];
}

System.out.print(sum);
}
}

class Main extends Parent {


public static void main(String args[]) {
int n;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
Main t = new Main();
t.fun(n);
}
}
Q2.
Problem Statement
Rithish is developing a straightforward pizza ordering system. To achieve this, he needs a Pizza class
with a constructor for the base price and topping cost, along with a calculatePrice method
overriding. He also wants a DiscountedPizza class that inherits from Pizza, applying a 10% discount
for more than three toppings.
The program prompts the user for inputs, creates instances of both classes, calculates regular and
discounted prices, and displays them formatted appropriately.
import java.util.Scanner;
import java.text.DecimalFormat;

class Pizza {
private double basePrice;
private double toppingCost;

public Pizza(double basePrice, double toppingCost) {


this.basePrice = basePrice;
this.toppingCost = toppingCost;
}

public double calculatePrice(int numberOfToppings) {


return basePrice + (numberOfToppings * toppingCost);
}
}

class DiscountedPizza extends Pizza {


public DiscountedPizza(double basePrice, double toppingCost) {
super(basePrice, toppingCost);
}

public double calculatePrice(int numberOfToppings) {


if (numberOfToppings > 3) {
return super.calculatePrice(numberOfToppings) * 0.9;
} else {
return super.calculatePrice(numberOfToppings);
}
}
}

public class Main {


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

double basePrice = scanner.nextDouble();


double toppingCost = scanner.nextDouble();
int numberOfToppings = scanner.nextInt();

Pizza pizza = new Pizza(basePrice, toppingCost);


DiscountedPizza discountedPizza = new DiscountedPizza(basePrice, toppingCost);

DecimalFormat df = new DecimalFormat("#.00");

double regularPrice = pizza.calculatePrice(numberOfToppings);


double discountedPrice = discountedPizza.calculatePrice(numberOfToppings);

System.out.println("Price without discount: Rs." + df.format(regularPrice));


System.out.println("Price with discount: Rs." + df.format(discountedPrice));

scanner.close();
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy