In Java, classes can be derived from other classes, allowing them to inherit fields and methods from the parent classes.
Definitions:
- A class derived from another class is known as a subclass (also called a derived class, extended class, or child class).
- The class from which a subclass is derived is known as a superclass (also called a base class or parent class).
Except for Object, which has no superclass, every class has exactly one direct superclass (single inheritance). If no other explicit superclass is declared, every class implicitly extends Object.
Classes can be derived from other classes, forming an inheritance chain that ultimately traces back to Object. A class in this chain is said to descend from all the classes up to Object.
Questions
Write a Java program to create a class called Animal
with a method called makeSound()
. Create a subclass called Cat
that overrides the makeSound()
method to meow.
See Answer
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Meow");
}
}
public class Main {
public static void main(String[] args) {
Cat cat = new Cat();
cat.makeSound();
}
}
Write a Java program to create a class called Vehicle
with a method called drive()
. Create a subclass called Car
that overrides the drive()
method to print “Driving a car”.
See Answer
class Vehicle {
void drive() {
System.out.println("Vehicle is driving");
}
}
class Car extends Vehicle {
@Override
void drive() {
System.out.println("Driving a car");
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.drive();
}
}
Write a Java program to create a class called Shape
with a method called getArea()
. Create a subclass called Rectangle
that overrides the getArea()
method to calculate the area of a rectangle.
See Answer
class Shape {
double getArea() {
return 0;
}
}
class Rectangle extends Shape {
double length;
double width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
double getArea() {
return length * width;
}
}
public class Main {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5, 7);
System.out.println("Area of rectangle: " + rectangle.getArea());
}
}
Write a Java program to create a class called Employee
with methods called work()
and getSalary()
. Create a subclass called HRManager
that overrides the work()
method and adds a new method called addEmployee()
.
See Answer
class Employee {
void work() {
System.out.println("Employee is working");
}
double getSalary() {
return 50000;
}
}
class HRManager extends Employee {
@Override
void work() {
System.out.println("HR Manager is working");
}
void addEmployee() {
System.out.println("Adding a new employee");
}
}
public class Main {
public static void main(String[] args) {
HRManager hrManager = new HRManager();
hrManager.work();
hrManager.addEmployee();
System.out.println("Salary: " + hrManager.getSalary());
}
}
Write a Java program to create a class known as BankAccount
with methods called deposit()
and withdraw()
. Create a subclass called SavingsAccount
that overrides the withdraw()
method to prevent withdrawals if the account balance falls below one hundred.
See Answer
class BankAccount {
double balance;
void deposit(double amount) {
balance += amount;
}
void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
} else {
System.out.println("Insufficient balance");
}
}
double getBalance() {
return balance;
}
}
class SavingsAccount extends BankAccount {
@Override
void withdraw(double amount) {
if (balance - amount >= 100) {
balance -= amount;
} else {
System.out.println("Withdrawal denied. Minimum balance must be 100");
}
}
}
public class Main {
public static void main(String[] args) {
SavingsAccount sa = new SavingsAccount();
sa
WAP in Java to create a class Person
with properties name
and age
, and a method greet()
. Extend this class to a Student
class which adds a property grade
. Implement a displayGrade()
method in Student
that prints the grade.
See Answer
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
void greet() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
}
class Student extends Person {
String grade;
Student(String name, int age, String grade) {
super(name, age);
this.grade = grade;
}
void displayGrade() {
System.out.println("I am in grade " + grade + ".");
}
public static void main(String[] args) {
Student student = new Student("John", 16, "10th");
student.greet();
student.displayGrade();
}
}
WAP in Java to extend the Person
class to a Teacher
class. Override the greet()
method in Teacher
to include the subject they teach.
See Answer
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
void greet() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
}
class Teacher extends Person {
String subject;
Teacher(String name, int age, String subject) {
super(name, age);
this.subject = subject;
}
@Override
void greet() {
System.out.println("Hello, my name is " + name + ", I am " + age + " years old and I teach " + subject + ".");
}
public static void main(String[] args) {
Teacher teacher = new Teacher("Jane", 35, "Math");
teacher.greet();
}
}
WAP in Java to create a Teacher
class that extends Person
. Use the super
keyword to call the greet()
method from the Person
class within the overridden greet()
method.
See Answer
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
void greet() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
}
class Teacher extends Person {
String subject;
Teacher(String name, int age, String subject) {
super(name, age);
this.subject = subject;
}
@Override
void greet() {
super.greet();
System.out.println("I teach " + subject + ".");
}
public static void main(String[] args) {
Teacher teacher = new Teacher("Jane", 35, "Science");
teacher.greet();
}
}
WAP in Java to create a Vehicle
class with a constructor that takes make
and model
. Extend this class to a Car
class and add a property year
. Use the super
keyword to call the parent class constructor.
See Answer
class Vehicle {
String make;
String model;
Vehicle(String make, String model) {
this.make = make;
this.model = model;
}
}
class Car extends Vehicle {
int year;
Car(String make, String model, int year) {
super(make, model);
this.year = year;
}
void displayInfo() {
System.out.println("This car is a " + year + " " + make + " " + model + ".");
}
public static void main(String[] args) {
Car car = new Car("Toyota", "Corolla", 2020);
car.displayInfo();
}
}
WAP in Java to create a class Animal
with a method sound()
. Extend this class to Dog
and Cat
classes, overriding the sound()
method to make respective animal sounds.
See Answer
class Animal {
void sound() {
System.out.println("Some generic animal sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Woof! Woof!");
}
}
class Cat extends Animal {
@Override
void sound() {
System.out.println("Meow! Meow!");
}
public static void main(String[] args) {
Dog dog = new Dog();
Cat cat = new Cat();
dog.sound();
cat.sound();
}
}
WAP in Java to create a class MathOperations
with a static method add(int a, int b)
. Extend this class to AdvancedMath
with a static method subtract(int a, int b)
.
See Answer
class MathOperations {
static int add(int a, int b) {
return a + b;
}
}
class AdvancedMath extends MathOperations {
static int subtract(int a, int b) {
return a - b;
}
public static void main(String[] args) {
System.out.println(MathOperations.add(5, 3)); // 8
System.out.println(AdvancedMath.subtract(5, 3)); // 2
}
}
WAP in Java to create a class Person
with properties firstName
and lastName
. Add getters and setters for fullName
. Extend this class to Employee
and include an additional property employeeId
.
See Answer
class Person {
private String firstName;
private String lastName;
Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFullName() {
return firstName + " " + lastName;
}
public void setFullName(String fullName) {
String[] parts = fullName.split(" ");
this.firstName = parts[0];
this.lastName = parts[1];
}
}
class Employee extends Person {
private String employeeId;
Employee(String firstName, String lastName, String employeeId) {
super(firstName, lastName);
this.employeeId = employeeId;
}
void displayEmployeeInfo() {
System.out.println("Employee ID: " + employeeId + ", Name: " + getFullName());
}
public static void main(String[] args) {
Employee emp = new Employee("John", "Doe", "E123");
emp.displayEmployeeInfo(); // Employee ID: E123, Name: John Doe
emp.setFullName("Jane Smith");
emp.displayEmployeeInfo(); // Employee ID: E123, Name: Jane Smith
}
}
WAP in Java to create a class Shape
with a method area()
. Extend this class to Rectangle
and Circle
classes, implementing the area()
method. Create an array of different shapes and calculate their areas.
See Answer
abstract class Shape {
abstract double area();
}
class Rectangle extends Shape {
double width, height;
Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
double area() {
return width * height;
}
}
class Circle extends Shape {
double radius;
Circle(double radius) {
this.radius = radius;
}
@Override
double area() {
return Math.PI * radius * radius;
}
public static void main(String[] args) {
Shape[] shapes = {
new Rectangle(10, 20),
new Circle(10)
};
for (Shape shape : shapes) {
System.out.println("Area: " + shape.area());
}
}
}
WAP in Java to create an abstract class Shape
with an abstract method area()
. Extend this class to Rectangle
and Circle
classes, providing implementations for the area()
method.
See Answer
abstract class Shape {
abstract double area();
}
class Rectangle extends Shape {
double width, height;
Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
double area() {
return width * height;
}
}
class Circle extends Shape {
double radius;
Circle(double radius) {
this.radius = radius;
}
@Override
double area() {
return Math.PI * radius * radius;
}
public static void main(String[] args) {
Shape rectangle = new Rectangle(10, 20);
Shape circle = new Circle(10);
System.out.println("Rectangle area: " + rectangle.area());
System.out.println("Circle area: " + circle.area());
}
}
WAP in Java to create a class Employee
with a method calculateSalary()
. Extend this class to PermanentEmployee
and ContractEmployee
, overriding the calculateSalary()
method to calculate salaries differently.
See Answer
class Employee {
String name;
Employee(String name) {
this.name = name;
}
double calculateSalary() {
return 0;
}
}
class PermanentEmployee extends Employee {
double annualSalary;
PermanentEmployee(String name, double annualSalary) {
super(name);
this.annualSalary = annualSalary;
}
@Override
double calculateSalary() {
return annualSalary / 12;
}
}
class ContractEmployee extends Employee {
double hourlyRate;
int hoursWorked;
ContractEmployee(String name, double hourlyRate, int hoursWorked) {
super(name);
this.hourlyRate = hourlyRate;
this.hoursWorked = hoursWorked;
}
@Override
double calculateSalary() {
return hourlyRate * hoursWorked;
}
public static void main(String[] args) {
Employee permEmp = new PermanentEmployee("John", 60000);
Employee contractEmp = new ContractEmployee("Jane", 50, 160);
System.out.println("Permanent Employee Salary: " + permEmp.calculateSalary());
System.out.println("Contract Employee Salary: " + contractEmp.calculateSalary());
}
}
WAP in Java to create two interfaces Printable
and Showable
, both with a method print()
. Implement these interfaces in a class Document
and override the print()
method.
See Answer
interface Printable {
void print();
}
interface Showable {
void print();
}
class Document implements Printable, Showable {
@Override
public void print() {
System.out.println("Printing document...");
}
public static void main(String[] args) {
Document doc = new Document();
doc.print();
}
}
WAP in Java to create an interface Vehicle
with a default method start()
. Implement this interface in a class Car
and override the start()
method.
See Answer
interface Vehicle {
default void start() {
System.out.println("Starting the vehicle...");
}
}
class Car implements Vehicle {
@Override
public void start() {
System.out.println("Starting the car...");
}
public static void main(String[] args) {
Car car = new Car();
car.start();
}
}
WAP in Java to create a class Person
with a method greet()
. Extend this class to Employee
and override the greet()
method. Use the super
keyword to call the parent class method inside the overridden method.
See Answer
class Person {
void greet() {
System.out.println("Hello from Person!");
}
}
class Employee extends Person {
@Override
void greet() {
super.greet();
System.out.println("Hello from Employee!");
}
public static void main(String[] args) {
Employee emp = new Employee();
emp.greet();
}
}
WAP in Java to create a class Person
with a constructor that takes name
and age
. Extend this class to Employee
and add a property salary
. Use the super
keyword to call the parent class constructor.
See Answer
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
class Employee extends Person {
double salary;
Employee(String name, int age, double salary) {
super(name, age);
this.salary = salary;
}
void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age + ", Salary: " + salary);
}
public static void main(String[] args) {
Employee emp = new Employee("John", 30, 50000);
emp.displayInfo();
}
}
WAP in Java to create an abstract class Animal
with an abstract method sound()
. Extend this class to Dog
and Cat
classes, providing implementations for the sound()
method.
See Answer
abstract class Animal {
abstract void sound();
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Woof! Woof!");
}
}
class Cat extends Animal {
@Override
void sound() {
System.out.println("Meow! Meow!");
}
public static void main(String[] args) {
Dog dog = new Dog();
Cat cat = new Cat();
dog.sound();
cat.sound();
}
}
WAP in Java to create a class Calculator
with a method add(int a, int b)
. Extend this class to AdvancedCalculator
and overload the add
method to accept three integers.
See Answer
class Calculator {
int add(int a, int b) {
return a + b;
}
}
class AdvancedCalculator extends Calculator {
int add(int a, int b, int c) {
return a + b + c;
}
public static void main(String[] args) {
AdvancedCalculator calc = new AdvancedCalculator();
System.out.println("Sum of 2 and 3: " + calc.add(2, 3)); // 5
System.out.println("Sum of 2, 3 and 4: " + calc.add(2, 3, 4)); // 9
}
}
WAP in Java to create a class Person
with protected
properties name
and age
. Extend this class to Student
and access these properties in the Student
class.
See Answer
class Person {
protected String name;
protected int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
class Student extends Person {
String grade;
Student(String name, int age, String grade) {
super(name, age);
this.grade = grade;
}
void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age + ", Grade: " + grade);
}
public static void main(String[] args) {
Student student = new Student("John", 16, "10th");
student.displayInfo();
}
}
WAP in Java to create a class Animal
with a method eat()
. Extend this class to Mammal
and override the eat()
method. Further extend Mammal
to Dog
and override the eat()
method again.
See Answer
class Animal {
void eat() {
System.out.println("Animal is eating...");
}
}
class Mammal extends Animal {
@Override
void eat() {
System.out.println("Mammal is eating...");
}
}
class Dog extends Mammal {
@Override
void eat() {
System.out.println("Dog is eating...");
}
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
}
}
WAP in Java to create a class Vehicle
with a final
method start()
. Extend this class to Car
and try to override the start()
method to demonstrate that it cannot be overridden.
See Answer
class Vehicle {
final void start() {
System.out.println("Starting the vehicle...");
}
}
class Car extends Vehicle {
// Uncommenting the below code will cause a compilation error
// @Override
// void start() {
// System.out.println("Starting the car...");
// }
public static void main(String[] args) {
Car car = new Car();
car.start();
}
}
WAP in Java to create an abstract class Appliance
with an abstract method turnOn()
. Create an interface RemoteControl
with a method operate()
. Implement these in a class Television
.
See Answer
abstract class Appliance {
abstract void turnOn();
}
interface RemoteControl {
void operate();
}
class Television extends Appliance implements RemoteControl {
@Override
void turnOn() {
System.out.println("Turning on the television...");
}
@Override
public void operate() {
System.out.println("Operating the television...");
}
public static void main(String[] args) {
Television tv = new Television();
tv.turnOn();
tv.operate();
}
}