INHERITANCE AND INTERFACE (SOME
POLYMORPHISM AND ABSTRACT)
1. Write a base class `Person` with attributes like `name` and `age`. Create a
subclass `Student` that inherits from `Person` and includes student-specific
attributes, such as `studentID` and `grade`. Write a main class that initializes a
student and displays their details.
Code:
import java.util.Scanner;
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
class Student extends Person {
int studentID;
float grade;
Student(String name, int age, int studentID, float grade) {
super(name, age);
this.studentID = studentID;
this.grade = grade;
}
void display() {
System.out.println("Name: " + name + "\nAge: " + age + "\nStudent ID: " +
studentID + "\nGrade: " + grade);
}
}
public class Main {
public static void main(String[] args) {
// Create a Scanner object to read input
Scanner sc = new Scanner(System.in);
// Get user input
System.out.print("Enter name: ");
String name = sc.nextLine();
System.out.print("Enter age: ");
int age = sc.nextInt();
System.out.print("Enter student ID: ");
int studentID = sc.nextInt();
System.out.print("Enter grade: ");
float grade = sc.nextFloat();
// Create a Student object with the provided values
Student s = new Student(name, age, studentID, grade);
// Display the student's details
s.display();
// Close the scanner to prevent resource leak
sc.close();
}
}
4. Create an interface `SpeedCalculator` with a method `calculateSpeed` for
calculating speed based on distance and time. Create a class `Vehicle` that includes
common attributes, such as , `model`, and `year`. Extend `Vehicle` with a class
`Car` and implement `SpeedCalculator` in it. In the main class, create a `Car`
object, calculate speed, and display vehicle details along with the speed.
import java.util.*;
interface SpeedCalculator {
double calculateSpeed(double distance, double time); // Method to calculate
speed
}
class Vehicle {
String model;
int year;
Vehicle(String model, int year) {
this.model = model;
this.year = year;
}
void display() {
System.out.println("Model: " + model + "\nYear: " + year);
}
}
class Car extends Vehicle implements SpeedCalculator {
String carType;
Car(String model, int year, String carType) {
super(model, year); // Call constructor of Vehicle
this.carType = carType;
}
@Override
public double calculateSpeed(double distance, double time) {
if (time == 0) {
return 0; // Avoid division by zero
}
return distance / time; // Speed = distance / time
}
@Override
void display() {
super.display(); // Display details from Vehicle
System.out.println("Car Type: " + carType);
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Get details for the car
System.out.print("Enter car model: ");
String model = sc.nextLine();
System.out.print("Enter car year: ");
int year = sc.nextInt();
sc.nextLine(); // Consume the newline character
System.out.print("Enter car type (e.g., Sedan, SUV): ");
String carType = sc.nextLine();
// Create a Car object
Car car = new Car(model, year, carType);
// Get distance and time for speed calculation
System.out.print("Enter distance traveled (in km): ");
double distance = sc.nextDouble();
System.out.print("Enter time taken (in hours): ");
double time = sc.nextDouble();
// Display car details
car.display();
// Calculate and display the speed
double speed = car.calculateSpeed(distance, time);
System.out.println("Calculated Speed: " + speed + " km/h");
sc.close(); // Close the scanner to prevent resource leak
}
}
5. Create two interfaces: `Adder` with a method `add` and `Multiplier` with a
method `multiply`. Create a class `Calculator` that implements both interfaces. In
the main class, create an instance of `Calculator`, use it to perform addition and
multiplication operations, and display the results.
interface Adder {
int add(int a, int b); // Method to add two integers
}
interface Multiplier {
int multiply(int a, int b); // Method to multiply two integers
}
class Calculator implements Adder, Multiplier {
@Override
public int add(int a, int b) {
return a + b; // Perform addition
}
@Override
public int multiply(int a, int b) {
return a * b; // Perform multiplication
}
}
public class Main {
public static void main(String[] args) {
// Create a Calculator object
Calculator calculator = new Calculator();
// Perform addition and multiplication operations
int num1 = 10, num2 = 5;
int sum = calculator.add(num1, num2); // Addition
int product = calculator.multiply(num1, num2); // Multiplication
// Display the results
System.out.println("Addition of " + num1 + " and " + num2 + " is: " + sum);
System.out.println("Multiplication of " + num1 + " and " + num2 + " is: " +
product);
}
}
6. Create a base class `Shape` with a method `area()` that returns 0. Then, create a
subclass `Circle` that calculates the area of a circle using the formula \( \pi r^2 \),
and a subclass `Rectangle` that calculates the area of a rectangle using \( \
text{length} \times \text{width} \).
import java.util.*;
abstract class shape{
abstract void area();
}
class Circle extends shape{
double r;
Circle(double r){
this.r=r;
}
void area(){
double pi=3.14;
double area=pi*(Math.pow(r,2));
System.out.println(area);
}
}
class rectangle extends shape{
double l;double w;
rectangle(double l,double w){
this.l=l;
this.w=w;
}
void area(){
double area=l*w;
System.out.println(area);
}
}
class Main{
public static void main(String args[]){
Scanner s=new Scanner(System.in);
double r,l,w;
System.out.println("rect or circle (1|2");
int n=s.nextInt();
if(n==1){
r=s.nextDouble();
shape sh=new Circle(r);
sh.area();
}
else if(n==2){
l=s.nextDouble();
w=s.nextDouble();
shape sh=new rectangle(l,w);
sh.area();
}
}
}
8. Create a base class `Account` with methods to calculate `interest()` and
`balance()`. Then, create two subclasses `SavingsAccount` that calculates interest
based on a savings rate, and `LoanAccount` that calculates interest based on a loan
rate.
import java.util.*;
class Account {
double p; // Principal amount
double r; // Interest rate
double t; // Time period in years
// Constructor to initialize principal, rate, and time
Account(double p, double r, double t) {
this.p = p;
this.r = r;
this.t = t;
}
// Method to calculate interest
public double interest() {
return p * r * t; // Simple interest formula
}
// Method to calculate the balance (Principal + Interest)
public double balance() {
return p + interest(); // Balance = Principal + Interest
}
}
class SavingAccount extends Account {
// Constructor for Savings Account
SavingAccount(double p, double r, double t) {
super(p, r, t); // Call parent constructor
}
// Override interest method if necessary (for specific savings rates, can adjust)
@Override
public double interest() {
return p * r * t; // Simple interest for savings account
}
// No need to override balance method as it works with the parent method
}
class LoanAccount extends Account {
// Constructor for Loan Account
LoanAccount(double p, double r, double t) {
super(p, r, t); // Call parent constructor
}
// Override interest method for loan interest calculation (can be adjusted if
different logic)
@Override
public double interest() {
return p * r * t; // Simple interest for loan account
}
// No need to override balance method as it works with the parent method
}
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
// Input for Savings and Loan Account
System.out.println("Enter principal for Saving Account:");
double savingPrincipal = s.nextDouble();
System.out.println("Enter interest rate for Saving Account:");
double savingRate = s.nextDouble();
System.out.println("Enter time (in years) for Saving Account:");
double savingTime = s.nextDouble();
System.out.println("Enter principal for Loan Account:");
double loanPrincipal = s.nextDouble();
System.out.println("Enter interest rate for Loan Account:");
double loanRate = s.nextDouble();
System.out.println("Enter time (in years) for Loan Account:");
double loanTime = s.nextDouble();
// Creating instances of SavingAccount and LoanAccount
SavingAccount sa = new SavingAccount(savingPrincipal, savingRate,
savingTime);
LoanAccount la = new LoanAccount(loanPrincipal, loanRate, loanTime);
// Display Saving Account details
System.out.println("\nSaving Account Details:");
System.out.println("Interest: " + sa.interest());
System.out.println("Balance: " + sa.balance());
// Display Loan Account details
System.out.println("\nLoan Account Details:");
System.out.println("Interest: " + la.interest());
System.out.println("Balance: " + la.balance());
}
}
10. Define two interfaces, `AddComplexNumbers` and
`MultiplyComplexNumbers`, with methods for addition and multiplication of
complex numbers. Then, create a class `ComplexNumberOperations` that
implements both interfaces to perform addition and multiplication of complex
numbers.
import java.util.Scanner;
interface AddComplexNumber {
ComplexNumber add(ComplexNumber c1, ComplexNumber c2);
}
interface MultiplyComplexNumber {
ComplexNumber multiply(ComplexNumber c1, ComplexNumber c2);
}
class ComplexNumber {
double real;
double imaginary;
ComplexNumber(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
void display() {
System.out.println(real + " + " + imaginary + "i");
}
}
class ComplexNumberOperations implements AddComplexNumber,
MultiplyComplexNumber {
@Override
public ComplexNumber add(ComplexNumber c1, ComplexNumber c2) {
double realSum = c1.real + c2.real;
double imaginarySum = c1.imaginary + c2.imaginary;
return new ComplexNumber(realSum, imaginarySum);
}
@Override
public ComplexNumber multiply(ComplexNumber c1, ComplexNumber c2) {
double realProduct = (c1.real * c2.real) - (c1.imaginary * c2.imaginary);
double imaginaryProduct = (c1.real * c2.imaginary) + (c1.imaginary *
c2.real);
return new ComplexNumber(realProduct, imaginaryProduct);
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read complex numbers from user input
System.out.println("Enter real and imaginary parts of the first complex
number:");
double real1 = scanner.nextDouble();
double imaginary1 = scanner.nextDouble();
System.out.println("Enter real and imaginary parts of the second complex
number:");
double real2 = scanner.nextDouble();
double imaginary2 = scanner.nextDouble();
ComplexNumber c1 = new ComplexNumber(real1, imaginary1);
ComplexNumber c2 = new ComplexNumber(real2, imaginary2);
ComplexNumberOperations operations = new
ComplexNumberOperations();
// Perform addition
ComplexNumber sum = operations.add(c1, c2);
System.out.print("Sum: ");
sum.display();
// Perform multiplication
ComplexNumber product = operations.multiply(c1, c2);
System.out.print("Product: ");
product.display();
scanner.close();
}
}
11. Create a base class `Shape3D` with a method `volume()` that returns 0. Then,
create subclasses `Sphere` and `Cylinder` that override the `volume()` method to
calculate the volume of the sphere (\( \frac{4}{3} \pi r^3 \)) and the cylinder (\( \pi
r^2 h \)) respectively.
import java.util.Scanner;
class Shape3D {
// Base method to be overridden in subclasses
double volume() {
return 0; // Default implementation, returns 0
}
}
class Sphere extends Shape3D {
double radius;
Sphere(double radius) {
this.radius = radius;
}
@Override
double volume() {
// Volume of a sphere: (4/3) * pi * r^3
return (4.0 / 3.0) * Math.PI * Math.pow(radius, 3);
}
}
class Cylinder extends Shape3D {
double radius;
double height;
Cylinder(double radius, double height) {
this.radius = radius;
this.height = height;
}
@Override
double volume() {
// Volume of a cylinder: pi * r^2 * h
return Math.PI * Math.pow(radius, 2) * height;
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input for Sphere
System.out.println("Enter the radius of the sphere:");
double sphereRadius = scanner.nextDouble();
Sphere sphere = new Sphere(sphereRadius);
System.out.println("Volume of the sphere: " + sphere.volume());
// Input for Cylinder
System.out.println("Enter the radius and height of the cylinder:");
double cylinderRadius = scanner.nextDouble();
double cylinderHeight = scanner.nextDouble();
Cylinder cylinder = new Cylinder(cylinderRadius, cylinderHeight);
System.out.println("Volume of the cylinder: " + cylinder.volume());
scanner.close();
}
}
14. Create a class `Fibonacci` that has a method `generateFibonacci(int n)` to
generate and print the first `n` Fibonacci numbers. Implement the Fibonacci series
logic using either recursion or iteration.
import java.util.Scanner;
class Fibonacci {
// Method to generate and print the first n Fibonacci numbers
public void generateFibonacci(int n) {
int a = 0, b = 1;
System.out.println("First " + n + " Fibonacci numbers:");
// Handle edge case for n = 1
if (n == 1) {
System.out.println(a);
return;
}
System.out.print(a + " " + b + " ");
// Iterative logic to generate Fibonacci numbers
for (int i = 2; i < n; i++) {
int next = a + b;
System.out.print(next + " ");
a = b;
b = next;
}
System.out.println(); // To end the output with a new line
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Take user input for the number of Fibonacci numbers to generate
System.out.print("Enter the number of Fibonacci numbers to generate: ");
int n = scanner.nextInt();
Fibonacci fibonacci = new Fibonacci();
fibonacci.generateFibonacci(n);
scanner.close();
}
}
1. Write a class named `Person` with attributes like `name` and `age`. Then, create
a subclass `Student` that inherits from `Person` and includes student-specific
attributes, such as `studentID` and `grade`. Implement methods for adding courses
and grades, updating grades, and printing a report card. Write a main class that
initializes a student, adds courses, updates grades, and displays the report card.
---
2. Create a class `LibraryItem` with attributes `title`, `author`, and `isAvailable`.
Create subclasses `Book` and `Magazine` that inherit from `LibraryItem` and add
specific attributes (e.g., ISBN for `Book` and issue number for `Magazine`).
Implement methods for borrowing and returning items, and display item details.
Write a main class that initializes a book and a magazine, borrows them, and
returns them.
---
3. Write a base class `Employee` with attributes like `name`, `role`, and `salary`.
Then, create two subclasses: `Manager`, which adds a `teamSize` attribute, and
`Developer`, which adds a `programmingLanguage` attribute. Implement methods
for displaying employee details and promoting employees. Write a main class that
creates a manager and a developer, promotes them, and displays their details.
---
Let me know if you'd like more!