0% found this document useful (0 votes)
3 views117 pages

Java OOP Practical Question Bank

The document is a comprehensive Java OOP practical question bank designed for MSE 1, MSE 2, and ESE syllabi, featuring 5-10 Eclipse-ready code examples for each topic. It covers various fundamental concepts such as basic Java syntax, class and object creation, constructors, method overloading, and the static keyword. Each program is accompanied by explanations and sample outputs to facilitate hands-on practice for exam preparation.

Uploaded by

kaustubhwani04
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)
3 views117 pages

Java OOP Practical Question Bank

The document is a comprehensive Java OOP practical question bank designed for MSE 1, MSE 2, and ESE syllabi, featuring 5-10 Eclipse-ready code examples for each topic. It covers various fundamental concepts such as basic Java syntax, class and object creation, constructors, method overloading, and the static keyword. Each program is accompanied by explanations and sample outputs to facilitate hands-on practice for exam preparation.

Uploaded by

kaustubhwani04
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

Java OOP Practical Question Bank

(Eclipse Ready)
This document provides a comprehensive collection of Java OOP practical programs,
tailored to your syllabus for MSE 1, MSE 2, and ESE. Each topic includes 5-10 Eclipse-
ready code examples designed for hands-on practice and to help you score highly in
your exam.

MSE 1 Syllabus
1. BASIC JAVA
Program 1.1: Hello World Program
// Filename: [Link]
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!"); // Prints "Hello, World!" to
the console
}
}

Program 1.2: Basic Data Types and Variables


// Filename: [Link]
public class DataTypes {
public static void main(String[] args) {
int integerVar = 10; // Integer type
double doubleVar = 20.5; // Double type
char charVar = 'A'; // Character type
boolean booleanVar = true; // Boolean type
String stringVar = "Java OOP"; // String type

[Link]("Integer: " + integerVar);


[Link]("Double: " + doubleVar);
[Link]("Char: " + charVar);
[Link]("Boolean: " + booleanVar);
[Link]("String: " + stringVar);
}
}

Program 1.3: Arithmetic Operations


// Filename: [Link]
public class ArithmeticOps {
public static void main(String[] args) {
int a = 10;
int b = 5;

[Link]("a + b = " + (a + b)); // Addition


[Link]("a - b = " + (a - b)); // Subtraction
[Link]("a * b = " + (a * b)); // Multiplication
[Link]("a / b = " + (a / b)); // Division
[Link]("a % b = " + (a % b)); // Modulus
}
}

Program 1.4: Conditional Statements (if-else)


// Filename: [Link]
public class ConditionalStatements {
public static void main(String[] args) {
int number = 15;

if (number % 2 == 0) {
[Link](number + " is an even number.");
} else {
[Link](number + " is an odd number.");
}
}
}

Program 1.5: Loop Statements (for loop)


// Filename: [Link]
public class ForLoopExample {
public static void main(String[] args) {
[Link]("Numbers from 1 to 5:");
for (int i = 1; i <= 5; i++) {
[Link](i);
}
}
}

Program 1.6: User Input using Scanner


// Filename: [Link]
import [Link];

public class UserInput {


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

[Link]("Enter your name: ");


String name = [Link](); // Read user input

[Link]("Enter your age: ");


int age = [Link](); // Read integer input

[Link]("Hello, " + name + ". You are " + age + " years
old.");

[Link](); // Close the scanner


}
}

Program 1.7: Finding Largest of Three Numbers


// Filename: [Link]
public class LargestOfThree {
public static void main(String[] args) {
int num1 = 10, num2 = 25, num3 = 15;

if (num1 >= num2 && num1 >= num3) {


[Link](num1 + " is the largest number.");
} else if (num2 >= num1 && num2 >= num3) {
[Link](num2 + " is the largest number.");
} else {
[Link](num3 + " is the largest number.");
}
}
}

2. CLASS & OBJECT


Program 2.1: Simple Class and Object Creation
// Filename: [Link]
class Dog {
String name;
String breed;

void bark() {
[Link](name + " barks!");
}
}

// Filename: [Link]
public class TestDog {
public static void main(String[] args) {
Dog myDog = new Dog(); // Create an object of Dog class
[Link] = "Buddy"; // Set object's state
[Link] = "Golden Retriever";

[Link]("Dog's Name: " + [Link]);


[Link]("Dog's Breed: " + [Link]);
[Link](); // Call object's behavior
}
}

Program 2.2: Class with Multiple Objects


// Filename: [Link]
class Car {
String make;
String model;
int year;

void displayCarInfo() {
[Link]("Make: " + make + ", Model: " + model + ", Year:
" + year);
}
}

// Filename: [Link]
public class TestCar {
public static void main(String[] args) {
Car car1 = new Car();
[Link] = "Toyota";
[Link] = "Camry";
[Link] = 2020;
[Link]();

Car car2 = new Car();


[Link] = "Honda";
[Link] = "Civic";
[Link] = 2022;
[Link]();
}
}

Program 2.3: Class with Methods and Return Values


// Filename: [Link]
class Calculator {
int add(int a, int b) {
return a + b;
}

int subtract(int a, int b) {


return a - b;
}
}

// Filename: [Link]
public class TestCalculator {
public static void main(String[] args) {
Calculator calc = new Calculator();
int sum = [Link](10, 5);
int difference = [Link](10, 5);

[Link]("Sum: " + sum);


[Link]("Difference: " + difference);
}
}

Program 2.4: Using this keyword to refer to current object


// Filename: [Link]
class Student {
int rollNo;
String name;

void setStudent(int rollNo, String name) {


[Link] = rollNo; // 'this' refers to the current object's
rollNo
[Link] = name; // 'this' refers to the current object's name
}

void displayStudent() {
[Link]("Roll No: " + rollNo + ", Name: " + name);
}
}

// Filename: [Link]
public class TestStudent {
public static void main(String[] args) {
Student s1 = new Student();
[Link](101, "Alice");
[Link]();
}
}

Program 2.5: Passing Objects as Arguments


// Filename: [Link]
class Rectangle {
int length, width;

Rectangle(int length, int width) {


[Link] = length;
[Link] = width;
}

boolean isEqual(Rectangle otherRect) {


// Compare current object's dimensions with another Rectangle
object's dimensions
return ([Link] == [Link] && [Link] ==
[Link]);
}
}

// Filename: [Link]
public class TestRectangle {
public static void main(String[] args) {
Rectangle rect1 = new Rectangle(10, 20);
Rectangle rect2 = new Rectangle(10, 20);
Rectangle rect3 = new Rectangle(15, 25);

[Link]("Rect1 equals Rect2: " + [Link](rect2));


// true
[Link]("Rect1 equals Rect3: " + [Link](rect3));
// false
}
}

3. CONSTRUCTOR
Program 3.1: Default Constructor
// Filename: [Link]
class DefaultConstructor {
int value;

// If no constructor is explicitly defined, Java provides a default one.


// Here, we define it to show its effect.
DefaultConstructor() {
value = 0; // Default value assigned by constructor
[Link]("Default Constructor called. Value: " + value);
}

public static void main(String[] args) {


DefaultConstructor obj = new DefaultConstructor(); // Calls the
default constructor
}
}

Program 3.2: No-Argument Constructor


// Filename: [Link]
class Bike {
String name;

// No-argument constructor
Bike() {
name = "Hero"; // Initialize default name
[Link]("Bike created with name: " + name);
}

public static void main(String[] args) {


Bike myBike = new Bike(); // Calls the no-argument constructor
}
}

Program 3.3: Parameterized Constructor


// Filename: [Link]
class Employee {
int id;
String name;

// Parameterized constructor
Employee(int i, String n) {
id = i;
name = n;
[Link]("Employee created: ID=" + id + ", Name=" + name);
}

public static void main(String[] args) {


Employee emp1 = new Employee(101, "Alice"); // Calls parameterized
constructor
Employee emp2 = new Employee(102, "Bob");
}
}

Program 3.4: Constructor Overloading


// Filename: [Link]
class Box {
double width, height, depth;

// Constructor with no parameters


Box() {
width = height = depth = 0;
[Link]("No-argument constructor called.");
}

// Constructor with one parameter (for a cube)


Box(double side) {
width = height = depth = side;
[Link]("Cube constructor called. Side: " + side);
}

// Constructor with three parameters


Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
[Link]("Box constructor called. W:" + w + ", H:" + h +
", D:" + d);
}

double volume() {
return width * height * depth;
}

public static void main(String[] args) {


Box box1 = new Box(); // Calls no-argument constructor
[Link]("Volume of box1: " + [Link]());

Box cube = new Box(10); // Calls one-parameter constructor


[Link]("Volume of cube: " + [Link]());

Box box2 = new Box(10, 20, 15); // Calls three-parameter constructor


[Link]("Volume of box2: " + [Link]());
}
}

Program 3.5: Copy Constructor


// Filename: [Link]
class Student {
int id;
String name;

// Parameterized constructor
Student(int i, String n) {
id = i;
name = n;
}

// Copy constructor (copies values from another Student object)


Student(Student s) {
id = [Link];
name = [Link];
}

void display() {
[Link]("ID: " + id + ", Name: " + name);
}

public static void main(String[] args) {


Student s1 = new Student(111, "John");
Student s2 = new Student(s1); // s2 is a copy of s1

[Link]();
[Link]();
}
}

4. METHOD OVERLOADING
Program 4.1: Overloading by Number of Arguments
// Filename: [Link]
class Adder {
static int add(int a, int b) {
return a + b;
}

static int add(int a, int b, int c) {


return a + b + c;
}
}

public class OverloadByCount {


public static void main(String[] args) {
[Link]("Sum of two numbers: " + [Link](10, 20));
[Link]("Sum of three numbers: " + [Link](10, 20,
30));
}
}

Program 4.2: Overloading by Type of Arguments


// Filename: [Link]
class Calculator {
static int multiply(int a, int b) {
return a * b;
}

static double multiply(double a, double b) {


return a * b;
}
}

public class OverloadByType {


public static void main(String[] args) {
[Link]("Integer multiplication: " +
[Link](5, 10));
[Link]("Double multiplication: " +
[Link](5.5, 10.0));
}
}

Program 4.3: Overloading with Different Order of Arguments


// Filename: [Link]
class Printer {
void print(int a, String s) {
[Link]("Int: " + a + ", String: " + s);
}

void print(String s, int a) {


[Link]("String: " + s + ", Int: " + a);
}
}

public class OverloadByOrder {


public static void main(String[] args) {
Printer p = new Printer();
[Link](10, "Hello");
[Link]("World", 20);
}
}

Program 4.4: Method Overloading with Type Promotion


// Filename: [Link]
class OverloadDemo {
void test(int a, long b) {
[Link]("test(int a, long b) called");
}

void test(long a, int b) {


[Link]("test(long a, int b) called");
}

// This method will be called if no exact match is found and type


promotion is possible
void test(double a, double b) {
[Link]("test(double a, double b) called");
}
}

public class TypePromotion {


public static void main(String[] args) {
OverloadDemo od = new OverloadDemo();
[Link](10, 20L); // Calls test(int, long)
[Link](20L, 10); // Calls test(long, int)
[Link](10, 20); // Calls test(double, double) due to type
promotion (int to double)
}
}

Program 4.5: Ambiguity in Method Overloading


// Filename: [Link]
// This program demonstrates an ambiguous call in method overloading
class Ambiguous {
void method(int a, double b) {
[Link]("Method with int, double");
}

void method(double a, int b) {


[Link]("Method with double, int");
}

public static void main(String[] args) {


Ambiguous obj = new Ambiguous();
// [Link](10, 20); // This would cause a compile-time error
(ambiguous call)
// Java cannot decide whether to convert 10 to double or 20 to
double.
[Link]("Uncomment '[Link](10, 20);' to see compile-
time error.");
[Link](10, 20.0); // This is fine
[Link](10.0, 20); // This is fine
}
}

5. STATIC KEYWORD
Program 5.1: Static Variable
// Filename: [Link]
class Counter {
static int count = 0; // Static variable, shared by all objects

Counter() {
count++; // Increments each time an object is created
[Link]("Object created. Count: " + count);
}

public static void main(String[] args) {


Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
[Link]("Total objects created: " + [Link]);
}
}

Program 5.2: Static Method


// Filename: [Link]
class Calculator {
static int cube(int n) {
return n * n * n;
}
}

public class StaticMethod {


public static void main(String[] args) {
// Static method can be called directly using the class name
[Link]("Cube of 3 is: " + [Link](3));
}
}

Program 5.3: Static Block


// Filename: [Link]
public class StaticBlock {
static {
// This static block is executed exactly once when the class is
loaded
[Link]("Static block executed.");
}

public static void main(String[] args) {


[Link]("Main method executed.");
// The static block will be executed before the main method
}
}

Program 5.4: Static vs Non-Static Members


// Filename: [Link]
class MyClass {
int instanceVar = 10; // Instance variable
static int staticVar = 20; // Static variable

void instanceMethod() {
[Link]("Instance method called.");
[Link]("Instance Var: " + instanceVar);
[Link]("Static Var from instance method: " + staticVar);
}

static void staticMethod() {


[Link]("Static method called.");
// [Link]("Instance Var: " + instanceVar); // ERROR:
Cannot access instanceVar from static method
[Link]("Static Var from static method: " + staticVar);
}
}

public class StaticNonStatic {


public static void main(String[] args) {
MyClass obj = new MyClass();
[Link](); // Call instance method using object

[Link](); // Call static method using class name


}
}

Program 5.5: Static Import


// Filename: [Link]
import static [Link]; // Static import for [Link]
import static [Link].*; // Static import for all static members
of Math class

public class StaticImport {


public static void main(String[] args) {
[Link]("Hello from static import!"); // No need for [Link]
[Link]("Max of 10 and 20: " + max(10, 20)); // No need for
[Link]
[Link]("PI value: " + PI);
}
}

MSE 2 Syllabus
1. Inheritance
Program 6.1: Single Inheritance
// Filename: [Link]
class Animal {
void eat() {
[Link]("Animal is eating.");
}
}

// Filename: [Link]
class Dog extends Animal { // Dog inherits from Animal
void bark() {
[Link]("Dog is barking.");
}
}

// Filename: [Link]
public class TestSingleInheritance {
public static void main(String[] args) {
Dog myDog = new Dog();
[Link](); // Method from Animal class
[Link](); // Method from Dog class
}
}

Program 6.2: Multilevel Inheritance


// Filename: [Link]
class Vehicle {
void drive() {
[Link]("Vehicle is driving.");
}
}

// Filename: [Link]
class Car extends Vehicle { // Car inherits from Vehicle
void changeGear() {
[Link]("Car is changing gear.");
}
}

// Filename: [Link]
class SportsCar extends Car { // SportsCar inherits from Car (multilevel)
void accelerate() {
[Link]("SportsCar is accelerating.");
}
}

// Filename: [Link]
public class TestMultilevelInheritance {
public static void main(String[] args) {
SportsCar mySportsCar = new SportsCar();
[Link](); // From Vehicle
[Link](); // From Car
[Link](); // From SportsCar
}
}

Program 6.3: Hierarchical Inheritance


// Filename: [Link]
class Shape {
void draw() {
[Link]("Drawing a shape.");
}
}

// Filename: [Link]
class Circle extends Shape { // Circle inherits from Shape
void drawCircle() {
[Link]("Drawing a circle.");
}
}

// Filename: [Link]
class Rectangle extends Shape { // Rectangle also inherits from Shape
void drawRectangle() {
[Link]("Drawing a rectangle.");
}
}

// Filename: [Link]
public class TestHierarchicalInheritance {
public static void main(String[] args) {
Circle c = new Circle();
[Link]();
[Link]();

Rectangle r = new Rectangle();


[Link]();
[Link]();
}
}

Program 6.4: Using super keyword with variables


// Filename: [Link]
class Parent {
String message = "Hello from Parent";
}

// Filename: [Link]
class Child extends Parent {
String message = "Hello from Child";

void display() {
[Link](message); // Refers to Child's message
[Link]([Link]); // Refers to Parent's message
}
}

// Filename: [Link]
public class TestSuperVariable {
public static void main(String[] args) {
Child c = new Child();
[Link]();
}
}

Program 6.5: Using super keyword with methods


// Filename: [Link]
class BaseClass {
void show() {
[Link]("BaseClass's show() method.");
}
}

// Filename: [Link]
class DerivedClass extends BaseClass {
void show() {
[Link](); // Calls BaseClass's show() method
[Link]("DerivedClass's show() method.");
}
}

// Filename: [Link]
public class TestSuperMethod {
public static void main(String[] args) {
DerivedClass d = new DerivedClass();
[Link]();
}
}

Program 6.6: Using super keyword with constructors


// Filename: [Link]
class SuperConstructorParent {
SuperConstructorParent() {
[Link]("Parent class constructor called.");
}
SuperConstructorParent(String msg) {
[Link]("Parent class constructor with message: " + msg);
}
}

// Filename: [Link]
class SuperConstructorChild extends SuperConstructorParent {
SuperConstructorChild() {
super(); // Calls Parent's no-arg constructor (implicitly called if
not present)
[Link]("Child class constructor called.");
}
SuperConstructorChild(String msg) {
super(msg); // Calls Parent's constructor with a String argument
[Link]("Child class constructor with message: " + msg);
}
}

// Filename: [Link]
public class TestSuperConstructor {
public static void main(String[] args) {
SuperConstructorChild c1 = new SuperConstructorChild();
SuperConstructorChild c2 = new SuperConstructorChild("Hello");
}
}

2. Method Overriding
Program 7.1: Basic Method Overriding
// Filename: [Link]
class VehicleOverride {
void run() {
[Link]("Vehicle is running.");
}
}

// Filename: [Link]
class Bike extends VehicleOverride {
@Override // Annotation to indicate method overriding
void run() {
[Link]("Bike is running safely at 60km/h.");
}
}

// Filename: [Link]
public class TestMethodOverriding {
public static void main(String[] args) {
Bike b = new Bike();
[Link](); // Calls the overridden run() method of Bike class
}
}

Program 7.2: Runtime Polymorphism (Dynamic Method Dispatch)


// Filename: [Link]
class AnimalPoly {
void makeSound() {
[Link]("Animal makes a sound.");
}
}

// Filename: [Link]
class Cat extends AnimalPoly {
@Override
void makeSound() {
[Link]("Cat meows.");
}
}

// Filename: [Link]
class DogPoly extends AnimalPoly {
@Override
void makeSound() {
[Link]("Dog barks.");
}
}

// Filename: [Link]
public class TestRuntimePoly {
public static void main(String[] args) {
AnimalPoly a; // Reference variable of parent class

a = new Cat(); // a refers to Cat object


[Link](); // Calls Cat's makeSound()

a = new DogPoly(); // a refers to Dog object


[Link](); // Calls Dog's makeSound()

a = new AnimalPoly(); // a refers to Animal object


[Link](); // Calls Animal's makeSound()
}
}

Program 7.3: Rules of Method Overriding (Return Type)


// Filename: [Link]
class ParentReturn {
Object getData() {
return new Object();
}
}

// Filename: [Link]
class ChildReturn extends ParentReturn {
@Override
String getData() { // Covariant return type: String is a subclass of
Object
return "Some String Data";
}
}

// Filename: [Link]
public class TestCovariantReturn {
public static void main(String[] args) {
ChildReturn c = new ChildReturn();
[Link]([Link]());
}
}

Program 7.4: final methods cannot be overridden


// Filename: [Link]
class FinalMethodParent {
final void display() {
[Link]("This is a final method.");
}
}

// Filename: [Link]
class FinalMethodChild extends FinalMethodParent {
// void display() { // ERROR: Cannot override the final method from
FinalMethodParent
// [Link]("Trying to override final method.");
// }
public static void main(String[] args) {
[Link]("Final methods cannot be overridden. Uncomment
the display() method in FinalMethodChild to see the compile-time error.");
}
}

Program 7.5: static methods cannot be overridden (Method Hiding)


// Filename: [Link]
class StaticMethodParent {
static void show() {
[Link]("Parent's static show() method.");
}
}

// Filename: [Link]
class StaticMethodChild extends StaticMethodParent {
static void show() { // This is method hiding, not overriding
[Link]("Child's static show() method.");
}
}

// Filename: [Link]
public class TestStaticMethodHiding {
public static void main(String[] args) {
[Link](); // Calls Parent's static method
[Link](); // Calls Child's static method

StaticMethodParent p = new StaticMethodChild();


[Link](); // Still calls Parent's static method (based on reference
type)
}
}

3. Abstract Class
Program 8.1: Simple Abstract Class and Method
// Filename: [Link]
abstract class VehicleAbstract {
abstract void run(); // Abstract method (no body)

void changeGear() { // Non-abstract method


[Link]("Gear changed.");
}
}

// Filename: [Link]
class Honda extends VehicleAbstract {
@Override
void run() {
[Link]("Honda is running safely.");
}
}

// Filename: [Link]
public class TestAbstractClass {
public static void main(String[] args) {
Honda honda = new Honda();
[Link]();
[Link]();
// VehicleAbstract v = new VehicleAbstract(); // ERROR: Cannot
instantiate abstract class
}
}

Program 8.2: Abstract Class with Constructor


// Filename: [Link]
abstract class Bank {
String name;

Bank(String name) { // Constructor in abstract class


[Link] = name;
[Link]("Bank created: " + name);
}

abstract int getRateOfInterest();

void displayInfo() {
[Link]("This is a bank.");
}
}

// Filename: [Link]
class SBI extends Bank {
SBI() {
super("SBI Bank"); // Call abstract class constructor
}

@Override
int getRateOfInterest() {
return 7;
}
}

// Filename: [Link]
public class TestAbstractConstructor {
public static void main(String[] args) {
SBI sbi = new SBI();
[Link]("SBI Rate of Interest: " +
[Link]() + "%");
[Link]();
}
}

Program 8.3: Abstract Class with Concrete Methods


// Filename: [Link]
abstract class EmployeeAbstract {
String name;
int id;

EmployeeAbstract(String name, int id) {


[Link] = name;
[Link] = id;
}

abstract double calculateSalary(); // Abstract method

void displayEmployeeInfo() { // Concrete method


[Link]("Employee Name: " + name + ", ID: " + id);
}
}

// Filename: [Link]
class FullTimeEmployee extends EmployeeAbstract {
double monthlySalary;

FullTimeEmployee(String name, int id, double monthlySalary) {


super(name, id);
[Link] = monthlySalary;
}

@Override
double calculateSalary() {
return monthlySalary;
}
}

// Filename: [Link]
public class TestEmployeeAbstract {
public static void main(String[] args) {
FullTimeEmployee ft = new FullTimeEmployee("David", 1001, 50000);
[Link]();
[Link]("Full-time Employee Salary: " +
[Link]());
}
}

Program 8.4: Abstract Class for Template Method Pattern


// Filename: [Link]
abstract class Game {
abstract void initialize();
abstract void startPlay();
abstract void endPlay();

// Template method
public final void play() {
initialize();
startPlay();
endPlay();
}
}

// Filename: [Link]
class Cricket extends Game {
@Override
void initialize() {
[Link]("Cricket Game Initialized! Start playing.");
}

@Override
void startPlay() {
[Link]("Cricket Game Started. Enjoy the game!");
}

@Override
void endPlay() {
[Link]("Cricket Game Finished!");
}
}

// Filename: [Link]
public class TestGame {
public static void main(String[] args) {
Game game = new Cricket(); // Polymorphism
[Link]();
}
}

Program 8.5: Abstract Class with main method


// Filename: [Link]
abstract class AbstractWithMain {
abstract void abstractMethod();

public static void main(String[] args) {


[Link]("Main method in abstract class.");
// You can have a main method in an abstract class, but you still
can't instantiate it.
// To call abstractMethod, you'd need a concrete subclass.
}
}

// Filename: [Link]
class ConcreteSubclass extends AbstractWithMain {
@Override
void abstractMethod() {
[Link]("Implementation of abstract method.");
}

public static void main(String[] args) {


ConcreteSubclass obj = new ConcreteSubclass();
[Link]();
}
}

4. Interface
Program 9.1: Simple Interface Implementation
// Filename: [Link]
interface Drawable {
void draw(); // Implicitly public and abstract
}

// Filename: [Link]
class CircleImpl implements Drawable {
@Override
public void draw() { // Must be public
[Link]("Drawing a circle.");
}
}

// Filename: [Link]
public class TestInterface {
public static void main(String[] args) {
Drawable d = new CircleImpl(); // Polymorphism
[Link]();
}
}

Program 9.2: Multiple Inheritance with Interfaces


// Filename: [Link]
interface Printable {
void print();
}

// Filename: [Link]
interface Showable {
void show();
}

// Filename: [Link]
class MyClass implements Printable, Showable {
@Override
public void print() {
[Link]("Printing...");
}

@Override
public void show() {
[Link]("Showing...");
}
}

// Filename: [Link]
public class TestMultipleInheritance {
public static void main(String[] args) {
MyClass obj = new MyClass();
[Link]();
[Link]();
}
}

Program 9.3: Interface with Default Methods (Java 8+)


// Filename: [Link]
interface MyInterface {
void abstractMethod(); // Abstract method

default void defaultMethod() { // Default method with implementation


[Link]("This is a default method.");
}
}

// Filename: [Link]
class MyClassWithDefault implements MyInterface {
@Override
public void abstractMethod() {
[Link]("Implementing abstract method.");
}
}

// Filename: [Link]
public class TestDefaultMethod {
public static void main(String[] args) {
MyClassWithDefault obj = new MyClassWithDefault();
[Link]();
[Link](); // Call default method
}
}

Program 9.4: Interface with Static Methods (Java 8+)


// Filename: [Link]
interface CalculatorInterface {
int add(int a, int b);

static int multiply(int a, int b) { // Static method in interface


return a * b;
}
}

// Filename: [Link]
class SimpleCalculator implements CalculatorInterface {
@Override
public int add(int a, int b) {
return a + b;
}
}

// Filename: [Link]
public class TestStaticInterfaceMethod {
public static void main(String[] args) {
SimpleCalculator sc = new SimpleCalculator();
[Link]("Sum: " + [Link](5, 3));
// Call static method using interface name
[Link]("Product: " + [Link](5,
3));
}
}

Program 9.5: Interface Inheritance


// Filename: [Link]
interface A {
void methodA();
}

// Filename: [Link]
interface B extends A { // Interface B inherits from A
void methodB();
}

// Filename: [Link]
class MyClassInterfaceInheritance implements B {
@Override
public void methodA() {
[Link]("Implementing methodA from interface A.");
}

@Override
public void methodB() {
[Link]("Implementing methodB from interface B.");
}
}

// Filename: [Link]
public class TestInterfaceInheritance {
public static void main(String[] args) {
MyClassInterfaceInheritance obj = new MyClassInterfaceInheritance();
[Link]();
[Link]();
}
}

5. Exception Handling
Program 10.1: Basic Try-Catch Block (ArithmeticException)
// Filename: [Link]
public class BasicException {
public static void main(String[] args) {
try {
int data = 100 / 0; // This will throw an ArithmeticException
[Link](data);
} catch (ArithmeticException e) {
[Link]("Exception caught: " + [Link]());
}
[Link]("Rest of the code...");
}
}

Program 10.2: Multiple Catch Blocks


// Filename: [Link]
public class MultipleCatch {
public static void main(String[] args) {
try {
String s = null;
[Link]([Link]()); // NullPointerException

int a[] = new int[5];


a[10] = 50; // ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
[Link]("Arithmetic Exception: " + [Link]());
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("ArrayIndexOutOfBounds Exception: " +
[Link]());
} catch (NullPointerException e) {
[Link]("NullPointer Exception: " + [Link]());
} catch (Exception e) { // Generic exception handler
[Link]("General Exception: " + [Link]());
}
[Link]("Rest of the code...");
}
}

Program 10.3: finally Block


// Filename: [Link]
public class FinallyBlock {
public static void main(String[] args) {
try {
int data = 25 / 5;
[Link]("Result: " + data);
} catch (ArithmeticException e) {
[Link]("Exception: " + [Link]());
} finally {
[Link]("Finally block always executes.");
}

[Link]("\nAnother example with exception:");


try {
int data = 25 / 0;
[Link]("Result: " + data);
} catch (ArithmeticException e) {
[Link]("Exception: " + [Link]());
} finally {
[Link]("Finally block always executes.");
}
}
}

Program 10.4: throw keyword (Custom Exception)


// Filename: [Link]
class InvalidAgeException extends Exception {
InvalidAgeException(String message) {
super(message);
}
}

// Filename: [Link]
public class CustomExceptionDemo {
static void validate(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age is not valid to vote.");
} else {
[Link]("Welcome to vote.");
}
}

public static void main(String[] args) {


try {
validate(13);
} catch (InvalidAgeException e) {
[Link]("Caught an exception: " + [Link]());
}

try {
validate(20);
} catch (InvalidAgeException e) {
[Link]("Caught an exception: " + [Link]());
}
}
}

Program 10.5: throws keyword


// Filename: [Link]
import [Link];

public class ThrowsKeyword {


void m() throws IOException {
throw new IOException("Device error"); // Checked exception
}

void n() throws IOException {


m(); // Propagating the exception
}

void p() {
try {
n(); // Handling the exception
} catch (IOException e) {
[Link]("Exception handled: " + [Link]());
}
}

public static void main(String[] args) {


ThrowsKeyword obj = new ThrowsKeyword();
obj.p();
[Link]("Normal flow...");
}
}

Program 10.6: try-with-resources (Java 7+)


// Filename: [Link]
import [Link];
import [Link];

public class TryWithResources {


public static void main(String[] args) {
String data = "This is some data to write to a file.";

// try-with-resources automatically closes the resource


(FileOutputStream)
try (FileOutputStream fos = new FileOutputStream("[Link]")) {
[Link]([Link]());
[Link]("Data written to [Link] successfully.");
} catch (IOException e) {
[Link]("An error occurred: " + [Link]());
}
}
}

6. Packages
Program 11.1: Creating and Using a Simple Package
Step 1: Create a directory structure. Create a folder my_package inside your
project’s src folder. Inside my_package , create [Link] .
Step 2: [Link] content.
// Filename: [Link] (inside my_package folder)
package my_package;

public class MyClass {


public void display() {
[Link]("Hello from MyClass in my_package!");
}
}

Step 3: [Link] to use the package.


// Filename: [Link] (in default package or another package)
import my_package.MyClass; // Import the class from the package

public class Main {


public static void main(String[] args) {
MyClass obj = new MyClass();
[Link]();
}
}

Program 11.2: Package with Sub-package


Step 1: Create directory structure. com/example/util/[Link]
Step 2: [Link] content.
// Filename: [Link] (inside com/example/util folder)
package [Link];

public class StringUtils {


public static String toUpperCase(String text) {
return [Link]();
}
}

Step 3: [Link] to use the sub-package.


// Filename: [Link] (in default package or another package)
import [Link];

public class App {


public static void main(String[] args) {
String original = "hello world";
String upper = [Link](original);
[Link]("Original: " + original);
[Link]("Uppercase: " + upper);
}
}
Program 11.3: Using import * to import all classes
Step 1: Create a package shapes with [Link] and [Link]
Step 2: [Link] content.
// Filename: [Link] (inside shapes folder)
package shapes;

public class Circle {


public void draw() {
[Link]("Drawing Circle");
}
}

Step 3: [Link] content.


// Filename: [Link] (inside shapes folder)
package shapes;

public class Square {


public void draw() {
[Link]("Drawing Square");
}
}

Step 4: [Link] to use import shapes.*


// Filename: [Link]
import shapes.*; // Imports all classes from the 'shapes' package

public class TestShapes {


public static void main(String[] args) {
Circle c = new Circle();
[Link]();

Square s = new Square();


[Link]();
}
}

Program 11.4: Package Naming Convention


// Filename: com/mycompany/project/util/[Link]
package [Link];

public class Logger {


public void log(String message) {
[Link]("[LOG] " + message);
}
}

// Filename: [Link]
import [Link];

public class MainApp {


public static void main(String[] args) {
Logger logger = new Logger();
[Link]("Application started.");
}
}

Program 11.5: Accessing Package Members (Public, Protected, Default)


Step 1: Create pack1/[Link]
// Filename: [Link] (inside pack1 folder)
package pack1;

public class A {
public int publicVar = 10;
protected int protectedVar = 20;
int defaultVar = 30; // Default (package-private)
private int privateVar = 40; // Only accessible within class A

public void display() {


[Link]("Class A: public=" + publicVar + ", protected=" +
protectedVar + ", default=" + defaultVar);
}
}

Step 2: Create pack1/[Link] (same package)


// Filename: [Link] (inside pack1 folder)
package pack1;

public class B {
public void testAccess() {
A objA = new A();
[Link]("From Class B (same package):");
[Link]("Public Var: " + [Link]);
[Link]("Protected Var: " + [Link]);
[Link]("Default Var: " + [Link]);
// [Link]("Private Var: " + [Link]); // ERROR:
private access
}
}

Step 3: Create pack2/[Link] (different package, not subclass)


// Filename: [Link] (inside pack2 folder)
package pack2;

import pack1.A;

public class C {
public void testAccess() {
A objA = new A();
[Link]("From Class C (different package, not
subclass):");
[Link]("Public Var: " + [Link]);
// [Link]("Protected Var: " + [Link]); //
ERROR: protected access
// [Link]("Default Var: " + [Link]); //
ERROR: default access
}
}

Step 4: Create pack2/[Link] (different package, subclass)


// Filename: [Link] (inside pack2 folder)
package pack2;

import pack1.A;

public class D extends A { // D is a subclass of A


public void testAccess() {
[Link]("From Class D (different package, subclass):");
[Link]("Public Var: " + publicVar);
[Link]("Protected Var: " + protectedVar); // Accessible
via inheritance
// [Link]("Default Var: " + defaultVar); // ERROR:
default access
}
}

Step 5: [Link] (main class)


// Filename: [Link]
import pack1.A;
import pack1.B;
import pack2.C;
import pack2.D;

public class TestAccess {


public static void main(String[] args) {
A objA = new A();
[Link]();

B objB = new B();


[Link]();

C objC = new C();


[Link]();

D objD = new D();


[Link]();
}
}

ESE Syllabus
1. Multithreading
Program 12.1: Creating Thread by Extending Thread Class
// Filename: [Link]
class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
[Link]([Link]().getName() + ": " + i);
try {
[Link](500); // Pause for 500 milliseconds
} catch (InterruptedException e) {
[Link](e);
}
}
}
}

// Filename: [Link]
public class TestThreadExtension {
public static void main(String[] args) {
MyThread t1 = new MyThread();
[Link]("Thread-1"); // Set thread name
MyThread t2 = new MyThread();
[Link]("Thread-2");

[Link](); // Start the first thread


[Link](); // Start the second thread
}
}

Program 12.2: Creating Thread by Implementing Runnable Interface


// Filename: [Link]
class MyRunnable implements Runnable {
private String threadName;

MyRunnable(String name) {
threadName = name;
[Link]("Creating " + threadName);
}

@Override
public void run() {
[Link]("Running " + threadName);
try {
for (int i = 4; i > 0; i--) {
[Link]("Thread: " + threadName + ", " + i);
[Link](1000);
}
} catch (InterruptedException e) {
[Link]("Thread " + threadName + " interrupted.");
}
[Link]("Thread " + threadName + " exiting.");
}
}

// Filename: [Link]
public class TestRunnableImplementation {
public static void main(String[] args) {
MyRunnable runnable1 = new MyRunnable("Runnable-1");
Thread t1 = new Thread(runnable1); // Pass runnable object to Thread
constructor
[Link]();

MyRunnable runnable2 = new MyRunnable("Runnable-2");


Thread t2 = new Thread(runnable2);
[Link]();
}
}

Program 12.3: Thread Synchronization (Synchronized Method)


// Filename: [Link]
class Table {
synchronized void printTable(int n) { // Synchronized method
for (int i = 1; i <= 5; i++) {
[Link](n * i);
try {
[Link](400);
} catch (Exception e) {
[Link](e);
}
}
}
}

// Filename: [Link]
class MyThread1 extends Thread {
Table t;
MyThread1(Table t) {
this.t = t;
}
@Override
public void run() {
[Link](5);
}
}

// Filename: [Link]
class MyThread2 extends Thread {
Table t;
MyThread2(Table t) {
this.t = t;
}
@Override
public void run() {
[Link](100);
}
}

// Filename: [Link]
public class TestSynchronization {
public static void main(String[] args) {
Table obj = new Table(); // Only one object
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
[Link]();
[Link]();
}
}

Program 12.4: Thread Synchronization (Synchronized Block)


// Filename: [Link]
class SharedResource {
void printNumbers() {
[Link]([Link]().getName() + " entering
non-synchronized block.");
// Non-synchronized block
for (int i = 0; i < 3; i++) {
[Link]([Link]().getName() + " non-
sync: " + i);
try { [Link](100); } catch (InterruptedException e) {
[Link](); }
}

[Link]([Link]().getName() + " entering


synchronized block.");
// Synchronized block
synchronized (this) { // Synchronize on the current object
for (int i = 0; i < 3; i++) {
[Link]([Link]().getName() + "
sync: " + i);
try { [Link](100); } catch (InterruptedException e) {
[Link](); }
}
}
[Link]([Link]().getName() + " exiting
synchronized block.");
}
}

// Filename: [Link]
class ThreadA extends Thread {
SharedResource resource;
ThreadA(SharedResource resource) {
[Link] = resource;
}
@Override
public void run() {
[Link]();
}
}

// Filename: [Link]
class ThreadB extends Thread {
SharedResource resource;
ThreadB(SharedResource resource) {
[Link] = resource;
}
@Override
public void run() {
[Link]();
}
}

// Filename: [Link]
public class TestSynchronizedBlock {
public static void main(String[] args) {
SharedResource sr = new SharedResource();
ThreadA tA = new ThreadA(sr);
ThreadB tB = new ThreadB(sr);

[Link]("Thread-A");
[Link]("Thread-B");

[Link]();
[Link]();
}
}

Program 12.5: Thread Lifecycle (States)


// Filename: [Link]
public class ThreadStates implements Runnable {
public static Thread thread1;
public static ThreadStates obj;

public static void main(String[] args) {


obj = new ThreadStates();
thread1 = new Thread(obj); // Thread 1 created (NEW state)

[Link]("State of thread1 after creation: " +


[Link]());
[Link](); // Thread 1 moved to RUNNABLE state

[Link]("State of thread1 after calling start(): " +


[Link]());
}

@Override
public void run() {
Thread myThread = new Thread(new MyRunnableState());
[Link]("State of myThread after creation: " +
[Link]());
[Link]();

try {
[Link](100); // thread1 sleeps, myThread runs
} catch (InterruptedException e) {
[Link]();
}
[Link]("State of myThread after sleep: " +
[Link]());

try {
[Link](); // thread1 waits for myThread to die (WAITING
state)
} catch (InterruptedException e) {
[Link]();
}
[Link]("State of myThread after join: " +
[Link]()); // TERMINATED
[Link]("State of thread1 at end of run: " +
[Link]().getState());
}
}
// Filename: [Link]
class MyRunnableState implements Runnable {
@Override
public void run() {
try {
[Link](1500); // Simulate some work
} catch (InterruptedException e) {
[Link]();
}
[Link]("MyRunnableState thread finished.");
}
}

Program 12.6: Inter-thread Communication (wait(), notify(), notifyAll())


// Filename: [Link]
import [Link];
import [Link];

class ProducerConsumer {
List<Integer> list = new ArrayList<>();
int capacity = 5;

public void produce() throws InterruptedException {


int value = 0;
while (true) {
synchronized (this) {
while ([Link]() == capacity) {
wait(); // Producer waits if list is full
}
[Link]("Producer produced-" + value);
[Link](value++);
notify(); // Notify consumer that item is available
[Link](1000);
}
}
}

public void consume() throws InterruptedException {


while (true) {
synchronized (this) {
while ([Link]() == 0) {
wait(); // Consumer waits if list is empty
}
int val = [Link](0);
[Link]("Consumer consumed-" + val);
notify(); // Notify producer that space is available
[Link](1000);
}
}
}
}

// Filename: [Link]
public class TestProducerConsumer {
public static void main(String[] args) {
ProducerConsumer pc = new ProducerConsumer();

Thread producerThread = new Thread(() -> {


try {
[Link]();
} catch (InterruptedException e) {
[Link]();
}
});

Thread consumerThread = new Thread(() -> {


try {
[Link]();
} catch (InterruptedException e) {
[Link]();
}
});

[Link]();
[Link]();
}
}

2. Applets
Program 13.1: Simple “Hello World” Applet
Step 1: [Link]
// Filename: [Link]
import [Link];
import [Link];

/*
<applet code="[Link]" width="300" height="200">
</applet>
*/
public class HelloApplet extends Applet {
public void paint(Graphics g) {
[Link]("Hello World from Applet!", 50, 100);
}
}

To run this:
1. Save the file as [Link] .
2. Compile: javac [Link]
3. Run using AppletViewer: appletviewer [Link]
Program 13.2: Applet with Parameters
Step 1: [Link]
// Filename: [Link]
import [Link];
import [Link];

/*
<applet code="[Link]" width="300" height="200">
<param name="message" value="Welcome to Applets!">
</applet>
*/
public class ParamApplet extends Applet {
String message;

public void init() {


message = getParameter("message"); // Get parameter from HTML
if (message == null) {
message = "No message parameter found.";
}
}

public void paint(Graphics g) {


[Link](message, 50, 100);
}
}

To run this:
1. Save as [Link] .
2. Compile: javac [Link]
3. Run using AppletViewer: appletviewer [Link]
Program 13.3: Applet Lifecycle Methods Demonstration
Step 1: [Link]
// Filename: [Link]
import [Link];
import [Link];

/*
<applet code="[Link]" width="400" height="300">
</applet>
*/
public class LifecycleApplet extends Applet {
String msg = "";

public void init() {


msg += "init() called | ";
[Link]("init() called");
}

public void start() {


msg += "start() called | ";
[Link]("start() called");
}

public void paint(Graphics g) {


msg += "paint() called | ";
[Link](msg, 10, 50);
[Link]("paint() called");
}

public void stop() {


msg += "stop() called | ";
[Link]("stop() called");
}

public void destroy() {


msg += "destroy() called | ";
[Link]("destroy() called");
}
}

To run this:
1. Save as [Link] .
2. Compile: javac [Link]
3. Run using AppletViewer: appletviewer [Link]
4. Observe console output and applet window. Minimize/restore the applet
window to see stop() and start() calls. Close the AppletViewer to see
destroy() .

Program 13.4: Handling Mouse Events in Applet


Step 1: [Link]
// Filename: [Link]
import [Link];
import [Link];
import [Link];
import [Link];

/*
<applet code="[Link]" width="400" height="300">
</applet>
*/
public class MouseEventApplet extends Applet implements MouseListener {
String msg = "";
int x = 0, y = 0;

public void init() {


addMouseListener(this); // Register mouse listener
}

public void paint(Graphics g) {


[Link](msg, x, y);
}

// MouseListener methods
public void mouseClicked(MouseEvent e) {
x = [Link]();
y = [Link]();
msg = "Mouse Clicked at (" + x + ", " + y + ")";
repaint(); // Redraw the applet
}

public void mouseEntered(MouseEvent e) {


msg = "Mouse Entered";
repaint();
}

public void mouseExited(MouseEvent e) {


msg = "Mouse Exited";
repaint();
}

public void mousePressed(MouseEvent e) {


msg = "Mouse Pressed";
repaint();
}
public void mouseReleased(MouseEvent e) {
msg = "Mouse Released";
repaint();
}
}

To run this:
1. Save as [Link] .
2. Compile: javac [Link]
3. Run using AppletViewer: appletviewer [Link]
4. Interact with the applet using your mouse.
Program 13.5: Handling Keyboard Events in Applet
Step 1: [Link]
// Filename: [Link]
import [Link];
import [Link];
import [Link];
import [Link];

/*
<applet code="[Link]" width="400" height="300">
</applet>
*/
public class KeyEventApplet extends Applet implements KeyListener {
String msg = "";

public void init() {


addKeyListener(this); // Register key listener
setFocusable(true); // Make applet focusable for key events
}

public void paint(Graphics g) {


[Link](msg, 50, 100);
}

// KeyListener methods
public void keyPressed(KeyEvent e) {
msg = "Key Pressed: " + [Link]([Link]());
repaint();
}

public void keyReleased(KeyEvent e) {


msg = "Key Released: " + [Link]([Link]());
repaint();
}

public void keyTyped(KeyEvent e) {


msg = "Key Typed: " + [Link]();
repaint();
}
}

To run this:
1. Save as [Link] .
2. Compile: javac [Link]
3. Run using AppletViewer: appletviewer [Link]
4. Click on the applet window to give it focus, then press keys.
Prepared by Manus AI

2. Method Overriding
Program 7.1: Basic Method Overriding
// Filename: [Link]
class VehicleOverride {
void run() {
[Link]("Vehicle is running.");
}
}

// Filename: [Link]
class Bike extends VehicleOverride {
@Override // Annotation to indicate method overriding
void run() {
[Link]("Bike is running safely at 60km/h.");
}
}

// Filename: [Link]
public class TestMethodOverriding {
public static void main(String[] args) {
Bike b = new Bike();
[Link](); // Calls the overridden run() method of Bike class
}
}

Program 7.2: Runtime Polymorphism (Dynamic Method Dispatch)


// Filename: [Link]
class AnimalPoly {
void makeSound() {
[Link]("Animal makes a sound.");
}
}

// Filename: [Link]
class Cat extends AnimalPoly {
@Override
void makeSound() {
[Link]("Cat meows.");
}
}

// Filename: [Link]
class DogPoly extends AnimalPoly {
@Override
void makeSound() {
[Link]("Dog barks.");
}
}

// Filename: [Link]
public class TestRuntimePoly {
public static void main(String[] args) {
AnimalPoly a; // Reference variable of parent class

a = new Cat(); // a refers to Cat object


[Link](); // Calls Cat's makeSound()

a = new DogPoly(); // a refers to Dog object


[Link](); // Calls Dog's makeSound()

a = new AnimalPoly(); // a refers to Animal object


[Link](); // Calls Animal's makeSound()
}
}

Program 7.3: Rules of Method Overriding (Return Type)


// Filename: [Link]
class ParentReturn {
Object getData() {
return new Object();
}
}

// Filename: [Link]
class ChildReturn extends ParentReturn {
@Override
String getData() { // Covariant return type: String is a subclass of
Object
return "Some String Data";
}
}

// Filename: [Link]
public class TestCovariantReturn {
public static void main(String[] args) {
ChildReturn c = new ChildReturn();
[Link]([Link]());
}
}

Program 7.4: final methods cannot be overridden


// Filename: [Link]
class FinalMethodParent {
final void display() {
[Link]("This is a final method.");
}
}

// Filename: [Link]
class FinalMethodChild extends FinalMethodParent {
// void display() { // ERROR: Cannot override the final method from
FinalMethodParent
// [Link]("Trying to override final method.");
// }
public static void main(String[] args) {
[Link]("Final methods cannot be overridden. Uncomment
the display() method in FinalMethodChild to see the compile-time error.");
}
}

Program 7.5: static methods cannot be overridden (Method Hiding)


// Filename: [Link]
class StaticMethodParent {
static void show() {
[Link]("Parent's static show() method.");
}
}

// Filename: [Link]
class StaticMethodChild extends StaticMethodParent {
static void show() { // This is method hiding, not overriding
[Link]("Child's static show() method.");
}
}

// Filename: [Link]
public class TestStaticMethodHiding {
public static void main(String[] args) {
[Link](); // Calls Parent's static method
[Link](); // Calls Child's static method

StaticMethodParent p = new StaticMethodChild();


[Link](); // Still calls Parent's static method (based on reference
type)
}
}

3. Abstract Class
Program 8.1: Simple Abstract Class and Method
// Filename: [Link]
abstract class VehicleAbstract {
abstract void run(); // Abstract method (no body)

void changeGear() { // Non-abstract method


[Link]("Gear changed.");
}
}

// Filename: [Link]
class Honda extends VehicleAbstract {
@Override
void run() {
[Link]("Honda is running safely.");
}
}

// Filename: [Link]
public class TestAbstractClass {
public static void main(String[] args) {
Honda honda = new Honda();
[Link]();
[Link]();
// VehicleAbstract v = new VehicleAbstract(); // ERROR: Cannot
instantiate abstract class
}
}

Program 8.2: Abstract Class with Constructor


// Filename: [Link]
abstract class Bank {
String name;

Bank(String name) { // Constructor in abstract class


[Link] = name;
[Link]("Bank created: " + name);
}

abstract int getRateOfInterest();

void displayInfo() {
[Link]("This is a bank.");
}
}

// Filename: [Link]
class SBI extends Bank {
SBI() {
super("SBI Bank"); // Call abstract class constructor
}

@Override
int getRateOfInterest() {
return 7;
}
}

// Filename: [Link]
public class TestAbstractConstructor {
public static void main(String[] args) {
SBI sbi = new SBI();
[Link]("SBI Rate of Interest: " +
[Link]() + "%");
[Link]();
}
}

Program 8.3: Abstract Class with Concrete Methods


// Filename: [Link]
abstract class EmployeeAbstract {
String name;
int id;

EmployeeAbstract(String name, int id) {


[Link] = name;
[Link] = id;
}

abstract double calculateSalary(); // Abstract method

void displayEmployeeInfo() { // Concrete method


[Link]("Employee Name: " + name + ", ID: " + id);
}
}

// Filename: [Link]
class FullTimeEmployee extends EmployeeAbstract {
double monthlySalary;

FullTimeEmployee(String name, int id, double monthlySalary) {


super(name, id);
[Link] = monthlySalary;
}

@Override
double calculateSalary() {
return monthlySalary;
}
}

// Filename: [Link]
public class TestEmployeeAbstract {
public static void main(String[] args) {
FullTimeEmployee ft = new FullTimeEmployee("David", 1001, 50000);
[Link]();
[Link]("Full-time Employee Salary: " +
[Link]());
}
}

Program 8.4: Abstract Class for Template Method Pattern


// Filename: [Link]
abstract class Game {
abstract void initialize();
abstract void startPlay();
abstract void endPlay();

// Template method
public final void play() {
initialize();
startPlay();
endPlay();
}
}

// Filename: [Link]
class Cricket extends Game {
@Override
void initialize() {
[Link]("Cricket Game Initialized! Start playing.");
}

@Override
void startPlay() {
[Link]("Cricket Game Started. Enjoy the game!");
}

@Override
void endPlay() {
[Link]("Cricket Game Finished!");
}
}

// Filename: [Link]
public class TestGame {
public static void main(String[] args) {
Game game = new Cricket(); // Polymorphism
[Link]();
}
}

Program 8.5: Abstract Class with main method


// Filename: [Link]
abstract class AbstractWithMain {
abstract void abstractMethod();

public static void main(String[] args) {


[Link]("Main method in abstract class.");
// You can have a main method in an abstract class, but you still
can't instantiate it.
// To call abstractMethod, you'd need a concrete subclass.
}
}

// Filename: [Link]
class ConcreteSubclass extends AbstractWithMain {
@Override
void abstractMethod() {
[Link]("Implementation of abstract method.");
}

public static void main(String[] args) {


ConcreteSubclass obj = new ConcreteSubclass();
[Link]();
}
}

4. Interface
Program 9.1: Simple Interface Implementation
// Filename: [Link]
interface Drawable {
void draw(); // Implicitly public and abstract
}

// Filename: [Link]
class CircleImpl implements Drawable {
@Override
public void draw() { // Must be public
[Link]("Drawing a circle.");
}
}

// Filename: [Link]
public class TestInterface {
public static void main(String[] args) {
Drawable d = new CircleImpl(); // Polymorphism
[Link]();
}
}

Program 9.2: Multiple Inheritance with Interfaces


// Filename: [Link]
interface Printable {
void print();
}

// Filename: [Link]
interface Showable {
void show();
}

// Filename: [Link]
class MyClass implements Printable, Showable {
@Override
public void print() {
[Link]("Printing...");
}

@Override
public void show() {
[Link]("Showing...");
}
}

// Filename: [Link]
public class TestMultipleInheritance {
public static void main(String[] args) {
MyClass obj = new MyClass();
[Link]();
[Link]();
}
}

Program 9.3: Interface with Default Methods (Java 8+)


// Filename: [Link]
interface MyInterface {
void abstractMethod(); // Abstract method

default void defaultMethod() { // Default method with implementation


[Link]("This is a default method.");
}
}

// Filename: [Link]
class MyClassWithDefault implements MyInterface {
@Override
public void abstractMethod() {
[Link]("Implementing abstract method.");
}
}

// Filename: [Link]
public class TestDefaultMethod {
public static void main(String[] args) {
MyClassWithDefault obj = new MyClassWithDefault();
[Link]();
[Link](); // Call default method
}
}

Program 9.4: Interface with Static Methods (Java 8+)


// Filename: [Link]
interface CalculatorInterface {
int add(int a, int b);

static int multiply(int a, int b) { // Static method in interface


return a * b;
}
}

// Filename: [Link]
class SimpleCalculator implements CalculatorInterface {
@Override
public int add(int a, int b) {
return a + b;
}
}

// Filename: [Link]
public class TestStaticInterfaceMethod {
public static void main(String[] args) {
SimpleCalculator sc = new SimpleCalculator();
[Link]("Sum: " + [Link](5, 3));
// Call static method using interface name
[Link]("Product: " + [Link](5,
3));
}
}

Program 9.5: Interface Inheritance


// Filename: [Link]
interface A {
void methodA();
}

// Filename: [Link]
interface B extends A { // Interface B inherits from A
void methodB();
}

// Filename: [Link]
class MyClassInterfaceInheritance implements B {
@Override
public void methodA() {
[Link]("Implementing methodA from interface A.");
}

@Override
public void methodB() {
[Link]("Implementing methodB from interface B.");
}
}

// Filename: [Link]
public class TestInterfaceInheritance {
public static void main(String[] args) {
MyClassInterfaceInheritance obj = new MyClassInterfaceInheritance();
[Link]();
[Link]();
}
}

5. Exception Handling
Program 10.1: Basic Try-Catch Block (ArithmeticException)
// Filename: [Link]
public class BasicException {
public static void main(String[] args) {
try {
int data = 100 / 0; // This will throw an ArithmeticException
[Link](data);
} catch (ArithmeticException e) {
[Link]("Exception caught: " + [Link]());
}
[Link]("Rest of the code...");
}
}

Program 10.2: Multiple Catch Blocks


// Filename: [Link]
public class MultipleCatch {
public static void main(String[] args) {
try {
String s = null;
[Link]([Link]()); // NullPointerException

int a[] = new int[5];


a[10] = 50; // ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
[Link]("Arithmetic Exception: " + [Link]());
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("ArrayIndexOutOfBounds Exception: " +
[Link]());
} catch (NullPointerException e) {
[Link]("NullPointer Exception: " + [Link]());
} catch (Exception e) { // Generic exception handler
[Link]("General Exception: " + [Link]());
}
[Link]("Rest of the code...");
}
}

Program 10.3: finally Block


// Filename: [Link]
public class FinallyBlock {
public static void main(String[] args) {
try {
int data = 25 / 5;
[Link]("Result: " + data);
} catch (ArithmeticException e) {
[Link]("Exception: " + [Link]());
} finally {
[Link]("Finally block always executes.");
}

[Link]("\nAnother example with exception:");


try {
int data = 25 / 0;
[Link]("Result: " + data);
} catch (ArithmeticException e) {
[Link]("Exception: " + [Link]());
} finally {
[Link]("Finally block always executes.");
}
}
}

Program 10.4: throw keyword (Custom Exception)


// Filename: [Link]
class InvalidAgeException extends Exception {
InvalidAgeException(String message) {
super(message);
}
}

// Filename: [Link]
public class CustomExceptionDemo {
static void validate(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age is not valid to vote.");
} else {
[Link]("Welcome to vote.");
}
}

public static void main(String[] args) {


try {
validate(13);
} catch (InvalidAgeException e) {
[Link]("Caught an exception: " + [Link]());
}

try {
validate(20);
} catch (InvalidAgeException e) {
[Link]("Caught an exception: " + [Link]());
}
}
}

Program 10.5: throws keyword


// Filename: [Link]
import [Link];

public class ThrowsKeyword {


void m() throws IOException {
throw new IOException("Device error"); // Checked exception
}

void n() throws IOException {


m(); // Propagating the exception
}

void p() {
try {
n(); // Handling the exception
} catch (IOException e) {
[Link]("Exception handled: " + [Link]());
}
}

public static void main(String[] args) {


ThrowsKeyword obj = new ThrowsKeyword();
obj.p();
[Link]("Normal flow...");
}
}

Program 10.6: try-with-resources (Java 7+)


// Filename: [Link]
import [Link];
import [Link];

public class TryWithResources {


public static void main(String[] args) {
String data = "This is some data to write to a file.";

// try-with-resources automatically closes the resource


(FileOutputStream)
try (FileOutputStream fos = new FileOutputStream("[Link]")) {
[Link]([Link]());
[Link]("Data written to [Link] successfully.");
} catch (IOException e) {
[Link]("An error occurred: " + [Link]());
}
}
}

6. Packages
Program 11.1: Creating and Using a Simple Package
Step 1: Create a directory structure. Create a folder my_package inside your
project’s src folder. Inside my_package , create [Link] .
Step 2: [Link] content.
// Filename: [Link] (inside my_package folder)
package my_package;

public class MyClass {


public void display() {
[Link]("Hello from MyClass in my_package!");
}
}

Step 3: [Link] to use the package.


// Filename: [Link] (in default package or another package)
import my_package.MyClass; // Import the class from the package

public class Main {


public static void main(String[] args) {
MyClass obj = new MyClass();
[Link]();
}
}

Program 11.2: Package with Sub-package


Step 1: Create directory structure. com/example/util/[Link]
Step 2: [Link] content.
// Filename: [Link] (inside com/example/util folder)
package [Link];

public class StringUtils {


public static String toUpperCase(String text) {
return [Link]();
}
}

Step 3: [Link] to use the sub-package.


// Filename: [Link] (in default package or another package)
import [Link];

public class App {


public static void main(String[] args) {
String original = "hello world";
String upper = [Link](original);
[Link]("Original: " + original);
[Link]("Uppercase: " + upper);
}
}
Program 11.3: Using import * to import all classes
Step 1: Create a package shapes with [Link] and [Link]
Step 2: [Link] content.
// Filename: [Link] (inside shapes folder)
package shapes;

public class Circle {


public void draw() {
[Link]("Drawing Circle");
}
}

Step 3: [Link] content.


// Filename: [Link] (inside shapes folder)
package shapes;

public class Square {


public void draw() {
[Link]("Drawing Square");
}
}

Step 4: [Link] to use import shapes.*


// Filename: [Link]
import shapes.*; // Imports all classes from the 'shapes' package

public class TestShapes {


public static void main(String[] args) {
Circle c = new Circle();
[Link]();

Square s = new Square();


[Link]();
}
}

Program 11.4: Package Naming Convention


// Filename: com/mycompany/project/util/[Link]
package [Link];

public class Logger {


public void log(String message) {
[Link]("[LOG] " + message);
}
}

// Filename: [Link]
import [Link];

public class MainApp {


public static void main(String[] args) {
Logger logger = new Logger();
[Link]("Application started.");
}
}

Program 11.5: Accessing Package Members (Public, Protected, Default)


Step 1: Create pack1/[Link]
// Filename: [Link] (inside pack1 folder)
package pack1;

public class A {
public int publicVar = 10;
protected int protectedVar = 20;
int defaultVar = 30; // Default (package-private)
private int privateVar = 40; // Only accessible within class A

public void display() {


[Link]("Class A: public=" + publicVar + ", protected=" +
protectedVar + ", default=" + defaultVar);
}
}

Step 2: Create pack1/[Link] (same package)


// Filename: [Link] (inside pack1 folder)
package pack1;

public class B {
public void testAccess() {
A objA = new A();
[Link]("From Class B (same package):");
[Link]("Public Var: " + [Link]);
[Link]("Protected Var: " + [Link]);
[Link]("Default Var: " + [Link]);
// [Link]("Private Var: " + [Link]); // ERROR:
private access
}
}

Step 3: Create pack2/[Link] (different package, not subclass)


// Filename: [Link] (inside pack2 folder)
package pack2;

import pack1.A;

public class C {
public void testAccess() {
A objA = new A();
[Link]("From Class C (different package, not
subclass):");
[Link]("Public Var: " + [Link]);
// [Link]("Protected Var: " + [Link]); //
ERROR: protected access
// [Link]("Default Var: " + [Link]); //
ERROR: default access
}
}

Step 4: Create pack2/[Link] (different package, subclass)


// Filename: [Link] (inside pack2 folder)
package pack2;

import pack1.A;

public class D extends A { // D is a subclass of A


public void testAccess() {
[Link]("From Class D (different package, subclass):");
[Link]("Public Var: " + publicVar);
[Link]("Protected Var: " + protectedVar); // Accessible
via inheritance
// [Link]("Default Var: " + defaultVar); // ERROR:
default access
}
}

Step 5: [Link] (main class)


// Filename: [Link]
import pack1.A;
import pack1.B;
import pack2.C;
import pack2.D;

public class TestAccess {


public static void main(String[] args) {
A objA = new A();
[Link]();

B objB = new B();


[Link]();

C objC = new C();


[Link]();

D objD = new D();


[Link]();
}
}

ESE Syllabus
1. Multithreading
Program 12.1: Creating Thread by Extending Thread Class
// Filename: [Link]
class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
[Link]([Link]().getName() + ": " + i);
try {
[Link](500); // Pause for 500 milliseconds
} catch (InterruptedException e) {
[Link](e);
}
}
}
}

// Filename: [Link]
public class TestThreadExtension {
public static void main(String[] args) {
MyThread t1 = new MyThread();
[Link]("Thread-1"); // Set thread name
MyThread t2 = new MyThread();
[Link]("Thread-2");

[Link](); // Start the first thread


[Link](); // Start the second thread
}
}

Program 12.2: Creating Thread by Implementing Runnable Interface


// Filename: [Link]
class MyRunnable implements Runnable {
private String threadName;

MyRunnable(String name) {
threadName = name;
[Link]("Creating " + threadName);
}

@Override
public void run() {
[Link]("Running " + threadName);
try {
for (int i = 4; i > 0; i--) {
[Link]("Thread: " + threadName + ", " + i);
[Link](1000);
}
} catch (InterruptedException e) {
[Link]("Thread " + threadName + " interrupted.");
}
[Link]("Thread " + threadName + " exiting.");
}
}

// Filename: [Link]
public class TestRunnableImplementation {
public static void main(String[] args) {
MyRunnable runnable1 = new MyRunnable("Runnable-1");
Thread t1 = new Thread(runnable1); // Pass runnable object to Thread
constructor
[Link]();

MyRunnable runnable2 = new MyRunnable("Runnable-2");


Thread t2 = new Thread(runnable2);
[Link]();
}
}

Program 12.3: Thread Synchronization (Synchronized Method)


// Filename: [Link]
class Table {
synchronized void printTable(int n) { // Synchronized method
for (int i = 1; i <= 5; i++) {
[Link](n * i);
try {
[Link](400);
} catch (Exception e) {
[Link](e);
}
}
}
}

// Filename: [Link]
class MyThread1 extends Thread {
Table t;
MyThread1(Table t) {
this.t = t;
}
@Override
public void run() {
[Link](5);
}
}

// Filename: [Link]
class MyThread2 extends Thread {
Table t;
MyThread2(Table t) {
this.t = t;
}
@Override
public void run() {
[Link](100);
}
}

// Filename: [Link]
public class TestSynchronization {
public static void main(String[] args) {
Table obj = new Table(); // Only one object
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
[Link]();
[Link]();
}
}

Program 12.4: Thread Synchronization (Synchronized Block)


// Filename: [Link]
class SharedResource {
void printNumbers() {
[Link]([Link]().getName() + " entering
non-synchronized block.");
// Non-synchronized block
for (int i = 0; i < 3; i++) {
[Link]([Link]().getName() + " non-
sync: " + i);
try { [Link](100); } catch (InterruptedException e) {
[Link](); }
}

[Link]([Link]().getName() + " entering


synchronized block.");
// Synchronized block
synchronized (this) { // Synchronize on the current object
for (int i = 0; i < 3; i++) {
[Link]([Link]().getName() + "
sync: " + i);
try { [Link](100); } catch (InterruptedException e) {
[Link](); }
}
}
[Link]([Link]().getName() + " exiting
synchronized block.");
}
}

// Filename: [Link]
class ThreadA extends Thread {
SharedResource resource;
ThreadA(SharedResource resource) {
[Link] = resource;
}
@Override
public void run() {
[Link]();
}
}

// Filename: [Link]
class ThreadB extends Thread {
SharedResource resource;
ThreadB(SharedResource resource) {
[Link] = resource;
}
@Override
public void run() {
[Link]();
}
}

// Filename: [Link]
public class TestSynchronizedBlock {
public static void main(String[] args) {
SharedResource sr = new SharedResource();
ThreadA tA = new ThreadA(sr);
ThreadB tB = new ThreadB(sr);

[Link]("Thread-A");
[Link]("Thread-B");

[Link]();
[Link]();
}
}

Program 12.5: Thread Lifecycle (States)


// Filename: [Link]
public class ThreadStates implements Runnable {
public static Thread thread1;
public static ThreadStates obj;

public static void main(String[] args) {


obj = new ThreadStates();
thread1 = new Thread(obj); // Thread 1 created (NEW state)

[Link]("State of thread1 after creation: " +


[Link]());
[Link](); // Thread 1 moved to RUNNABLE state

[Link]("State of thread1 after calling start(): " +


[Link]());
}

@Override
public void run() {
Thread myThread = new Thread(new MyRunnableState());
[Link]("State of myThread after creation: " +
[Link]());
[Link]();

try {
[Link](100); // thread1 sleeps, myThread runs
} catch (InterruptedException e) {
[Link]();
}
[Link]("State of myThread after sleep: " +
[Link]());

try {
[Link](); // thread1 waits for myThread to die (WAITING
state)
} catch (InterruptedException e) {
[Link]();
}
[Link]("State of myThread after join: " +
[Link]()); // TERMINATED
[Link]("State of thread1 at end of run: " +
[Link]().getState());
}
}
// Filename: [Link]
class MyRunnableState implements Runnable {
@Override
public void run() {
try {
[Link](1500); // Simulate some work
} catch (InterruptedException e) {
[Link]();
}
[Link]("MyRunnableState thread finished.");
}
}

Program 12.6: Inter-thread Communication (wait(), notify(), notifyAll())


// Filename: [Link]
import [Link];
import [Link];

class ProducerConsumer {
List<Integer> list = new ArrayList<>();
int capacity = 5;

public void produce() throws InterruptedException {


int value = 0;
while (true) {
synchronized (this) {
while ([Link]() == capacity) {
wait(); // Producer waits if list is full
}
[Link]("Producer produced-" + value);
[Link](value++);
notify(); // Notify consumer that item is available
[Link](1000);
}
}
}

public void consume() throws InterruptedException {


while (true) {
synchronized (this) {
while ([Link]() == 0) {
wait(); // Consumer waits if list is empty
}
int val = [Link](0);
[Link]("Consumer consumed-" + val);
notify(); // Notify producer that space is available
[Link](1000);
}
}
}
}

// Filename: [Link]
public class TestProducerConsumer {
public static void main(String[] args) {
ProducerConsumer pc = new ProducerConsumer();

Thread producerThread = new Thread(() -> {


try {
[Link]();
} catch (InterruptedException e) {
[Link]();
}
});

Thread consumerThread = new Thread(() -> {


try {
[Link]();
} catch (InterruptedException e) {
[Link]();
}
});

[Link]();
[Link]();
}
}

2. Applets
Program 13.1: Simple “Hello World” Applet
Step 1: [Link]
// Filename: [Link]
import [Link];
import [Link];

/*
<applet code="[Link]" width="300" height="200">
</applet>
*/
public class HelloApplet extends Applet {
public void paint(Graphics g) {
[Link]("Hello World from Applet!", 50, 100);
}
}

To run this:
1. Save the file as [Link] .
2. Compile: javac [Link]
3. Run using AppletViewer: appletviewer [Link]
Program 13.2: Applet with Parameters
Step 1: [Link]
// Filename: [Link]
import [Link];
import [Link];

/*
<applet code="[Link]" width="300" height="200">
<param name="message" value="Welcome to Applets!">
</applet>
*/
public class ParamApplet extends Applet {
String message;

public void init() {


message = getParameter("message"); // Get parameter from HTML
if (message == null) {
message = "No message parameter found.";
}
}

public void paint(Graphics g) {


[Link](message, 50, 100);
}
}

To run this:
1. Save as [Link] .
2. Compile: javac [Link]
3. Run using AppletViewer: appletviewer [Link]
Program 13.3: Applet Lifecycle Methods Demonstration
Step 1: [Link]
// Filename: [Link]
import [Link];
import [Link];

/*
<applet code="[Link]" width="400" height="300">
</applet>
*/
public class LifecycleApplet extends Applet {
String msg = "";

public void init() {


msg += "init() called | ";
[Link]("init() called");
}

public void start() {


msg += "start() called | ";
[Link]("start() called");
}

public void paint(Graphics g) {


msg += "paint() called | ";
[Link](msg, 10, 50);
[Link]("paint() called");
}

public void stop() {


msg += "stop() called | ";
[Link]("stop() called");
}

public void destroy() {


msg += "destroy() called | ";
[Link]("destroy() called");
}
}

To run this:
1. Save as [Link] .
2. Compile: javac [Link]
3. Run using AppletViewer: appletviewer [Link]
4. Observe console output and applet window. Minimize/restore the applet
window to see stop() and start() calls. Close the AppletViewer to see
destroy() .

Program 13.4: Handling Mouse Events in Applet


Step 1: [Link]
// Filename: [Link]
import [Link];
import [Link];
import [Link];
import [Link];

/*
<applet code="[Link]" width="400" height="300">
</applet>
*/
public class MouseEventApplet extends Applet implements MouseListener {
String msg = "";
int x = 0, y = 0;

public void init() {


addMouseListener(this); // Register mouse listener
}

public void paint(Graphics g) {


[Link](msg, x, y);
}

// MouseListener methods
public void mouseClicked(MouseEvent e) {
x = [Link]();
y = [Link]();
msg = "Mouse Clicked at (" + x + ", " + y + ")";
repaint(); // Redraw the applet
}

public void mouseEntered(MouseEvent e) {


msg = "Mouse Entered";
repaint();
}

public void mouseExited(MouseEvent e) {


msg = "Mouse Exited";
repaint();
}

public void mousePressed(MouseEvent e) {


msg = "Mouse Pressed";
repaint();
}
public void mouseReleased(MouseEvent e) {
msg = "Mouse Released";
repaint();
}
}

To run this:
1. Save as [Link] .
2. Compile: javac [Link]
3. Run using AppletViewer: appletviewer [Link]
4. Interact with the applet using your mouse.
Program 13.5: Handling Keyboard Events in Applet
Step 1: [Link]
// Filename: [Link]
import [Link];
import [Link];
import [Link];
import [Link];

/*
<applet code="[Link]" width="400" height="300">
</applet>
*/
public class KeyEventApplet extends Applet implements KeyListener {
String msg = "";

public void init() {


addKeyListener(this); // Register key listener
setFocusable(true); // Make applet focusable for key events
}

public void paint(Graphics g) {


[Link](msg, 50, 100);
}

// KeyListener methods
public void keyPressed(KeyEvent e) {
msg = "Key Pressed: " + [Link]([Link]());
repaint();
}

public void keyReleased(KeyEvent e) {


msg = "Key Released: " + [Link]([Link]());
repaint();
}

public void keyTyped(KeyEvent e) {


msg = "Key Typed: " + [Link]();
repaint();
}
}

To run this:
1. Save as [Link] .
2. Compile: javac [Link]
3. Run using AppletViewer: appletviewer [Link]
4. Click on the applet window to give it focus, then press keys.
Prepared by Manus AI

1. Inheritance
Program 6.1: Single Inheritance
// Filename: [Link]
class Animal {
void eat() {
[Link]("Animal is eating.");
}
}

// Filename: [Link]
class Dog extends Animal { // Dog inherits from Animal
void bark() {
[Link]("Dog is barking.");
}
}

// Filename: [Link]
public class TestSingleInheritance {
public static void main(String[] args) {
Dog myDog = new Dog();
[Link](); // Method from Animal class
[Link](); // Method from Dog class
}
}

Program 6.2: Multilevel Inheritance


// Filename: [Link]
class Vehicle {
void drive() {
[Link]("Vehicle is driving.");
}
}

// Filename: [Link]
class Car extends Vehicle { // Car inherits from Vehicle
void changeGear() {
[Link]("Car is changing gear.");
}
}

// Filename: [Link]
class SportsCar extends Car { // SportsCar inherits from Car (multilevel)
void accelerate() {
[Link]("SportsCar is accelerating.");
}
}

// Filename: [Link]
public class TestMultilevelInheritance {
public static void main(String[] args) {
SportsCar mySportsCar = new SportsCar();
[Link](); // From Vehicle
[Link](); // From Car
[Link](); // From SportsCar
}
}

Program 6.3: Hierarchical Inheritance


// Filename: [Link]
class Shape {
void draw() {
[Link]("Drawing a shape.");
}
}

// Filename: [Link]
class Circle extends Shape { // Circle inherits from Shape
void drawCircle() {
[Link]("Drawing a circle.");
}
}

// Filename: [Link]
class Rectangle extends Shape { // Rectangle also inherits from Shape
void drawRectangle() {
[Link]("Drawing a rectangle.");
}
}

// Filename: [Link]
public class TestHierarchicalInheritance {
public static void main(String[] args) {
Circle c = new Circle();
[Link]();
[Link]();

Rectangle r = new Rectangle();


[Link]();
[Link]();
}
}

Program 6.4: Using super keyword with variables


// Filename: [Link]
class Parent {
String message = "Hello from Parent";
}

// Filename: [Link]
class Child extends Parent {
String message = "Hello from Child";

void display() {
[Link](message); // Refers to Child\'s message
[Link]([Link]); // Refers to Parent\'s message
}
}

// Filename: [Link]
public class TestSuperVariable {
public static void main(String[] args) {
Child c = new Child();
[Link]();
}
}

Program 6.5: Using super keyword with methods


// Filename: [Link]
class BaseClass {
void show() {
[Link]("BaseClass\'s show() method.");
}
}

// Filename: [Link]
class DerivedClass extends BaseClass {
void show() {
[Link](); // Calls BaseClass\'s show() method
[Link]("DerivedClass\'s show() method.");
}
}

// Filename: [Link]
public class TestSuperMethod {
public static void main(String[] args) {
DerivedClass d = new DerivedClass();
[Link]();
}
}

Program 6.6: Using super keyword with constructors


// Filename: [Link]
class SuperConstructorParent {
SuperConstructorParent() {
[Link]("Parent class constructor called.");
}
SuperConstructorParent(String msg) {
[Link]("Parent class constructor with message: " + msg);
}
}

// Filename: [Link]
class SuperConstructorChild extends SuperConstructorParent {
SuperConstructorChild() {
super(); // Calls Parent\'s no-arg constructor (implicitly called if
not present)
[Link]("Child class constructor called.");
}
SuperConstructorChild(String msg) {
super(msg); // Calls Parent\'s constructor with a String argument
[Link]("Child class constructor with message: " + msg);
}
}

// Filename: [Link]
public class TestSuperConstructor {
public static void main(String[] args) {
SuperConstructorChild c1 = new SuperConstructorChild();
SuperConstructorChild c2 = new SuperConstructorChild("Hello");
}
}

You might also like