0% found this document useful (0 votes)
40 views34 pages

PPL Unit 4

Inheritance in Java allows one class to inherit properties and methods from another, promoting code reuse and method overriding. The types of inheritance include single, multilevel, and hierarchical, while multiple inheritance is not supported through classes but can be achieved using interfaces. Additionally, Java provides exception handling mechanisms using try, catch, and finally keywords to manage runtime errors effectively.

Uploaded by

Vaibhav Joshi
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)
40 views34 pages

PPL Unit 4

Inheritance in Java allows one class to inherit properties and methods from another, promoting code reuse and method overriding. The types of inheritance include single, multilevel, and hierarchical, while multiple inheritance is not supported through classes but can be achieved using interfaces. Additionally, Java provides exception handling mechanisms using try, catch, and finally keywords to manage runtime errors effectively.

Uploaded by

Vaibhav Joshi
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
You are on page 1/ 34

Question:

What is inheritance? Explain the various types of inheritance used in Java with suitable examples.

Answer 1: In Simple English + Code + Simple Points

What is Inheritance?

• Inheritance is a feature in Java that allows one class to use (or inherit) properties and methods of
another class.

• It helps in code reuse and method overriding.

Keyword used: extends

Types of Inheritance in Java:

Java supports these types of inheritance:

1. Single Inheritance

One class inherits from one base class.

java

CopyEdit

class Animal {

void sound() {

System.out.println("Animal makes sound");

class Dog extends Animal {

void bark() {

System.out.println("Dog barks");

public static void main(String[] args) {

Dog d = new Dog();

d.sound(); // From Animal

d.bark(); // From Dog


}

2. Multilevel Inheritance

A class inherits from a class, and another class inherits from that class.

java

CopyEdit

class A {

void msgA() {

System.out.println("This is A");

class B extends A {

void msgB() {

System.out.println("This is B");

class C extends B {

void msgC() {

System.out.println("This is C");

public static void main(String[] args) {

C obj = new C();

obj.msgA(); // from A

obj.msgB(); // from B

obj.msgC(); // from C

}
3. Hierarchical Inheritance

Multiple classes inherit from the same base class.

java

CopyEdit

class Animal {

void eat() {

System.out.println("Animal eats");

class Cat extends Animal {

void meow() {

System.out.println("Cat meows");

class Horse extends Animal {

void neigh() {

System.out.println("Horse neighs");

public static void main(String[] args) {

Horse h = new Horse();

h.eat(); // from Animal

h.neigh(); // from Horse

Java does NOT support Multiple Inheritance using classes (to avoid ambiguity), but it is supported using
interfaces.
Extra Simple Points for Exam:

• Inheritance avoids code duplication.

• extends keyword is used.

• Base class = parent/superclass.

• Derived class = child/subclass.

• Helps in method overriding and dynamic method dispatch.

• Java allows:
Single
Multilevel
Hierarchical
Multiple (not through classes, only via interfaces)

Question:

Explain the following keywords of Java in detail:


i) try
ii) catch
iii) finally

Answer 1: In Simple English + Example Code

What are try, catch, and finally?

These keywords are used for exception handling in Java.


They help in handling runtime errors smoothly without crashing the program.

i) try

• The try block is used to write code that might throw an exception.

• It is always followed by catch or finally.

Example:

java

CopyEdit

try {

int a = 10 / 0; // May cause exception

ii) catch
• The catch block is used to handle the exception thrown from try block.

• It catches the error and prevents the program from crashing.

Example:

java

CopyEdit

try {

int a = 10 / 0;

} catch (ArithmeticException e) {

System.out.println("Cannot divide by zero");

iii) finally

• The finally block is always executed, whether exception is thrown or not.

• Used to close files, release resources, etc.

Example:

java

CopyEdit

try {

int a = 10 / 2;

} catch (Exception e) {

System.out.println("Error");

} finally {

System.out.println("Finally block always runs");

Simple Points to Write in Exam:

• try: Write risky code.

• catch: Handle error if it occurs.

• finally: Always runs – even if error occurs or not.

Question:
Define package used in Java. Explain syntax, use, CLASSPATH, and hierarchy of package with example.

Answer 1: In Simple English with Examples

What is a Package in Java?

• A package is a group of related classes and interfaces.

• It helps in organizing code and avoiding name conflicts.

Uses of Package:

• Code reusability

• Better organization of classes

• Avoids class name conflicts

• Supports access protection

Types of Packages:

1. Built-in packages (like java.util, java.io)

2. User-defined packages (created by programmers)

Syntax to Create Package:

java

CopyEdit

package mypackage;

public class MyClass {

public void display() {

System.out.println("Inside my package");

File must be saved as MyClass.java inside a folder named mypackage.

How to Use Package:


java

CopyEdit

import mypackage.MyClass;

class Test {

public static void main(String[] args) {

MyClass obj = new MyClass();

obj.display();

What is CLASSPATH?

• CLASSPATH tells the Java compiler where to find user-defined packages or classes.

• It is an environment variable.

Example (on command line):

bash

CopyEdit

set CLASSPATH=C:\JavaPrograms

Package Hierarchy:

You can have packages inside packages (nested).

java

CopyEdit

package college.department;

public class Student {

public void show() {

System.out.println("Department Student");

• Folder structure:
markdown

CopyEdit

college

└── department

└── Student.java

Extra Points for Exam:

• package keyword is used to declare a package.

• Use import to include classes from other packages.

• Helps in large project development.

• CLASSPATH is required to locate user-defined packages

Question:

Elaborate Method Overriding and Dynamic Method Dispatch in Java.

Answer 1: In Simple English with Examples

What is Method Overriding?

• Method overriding means redefining a method of the parent class in the child class with the same
name and parameters.

• It is used to provide specific implementation in the child class.

Rules for Method Overriding:

• Method name must be same.

• Parameters must be same.

• There must be inheritance.

• Only non-static and non-final methods can be overridden.

Example of Method Overriding:

java

CopyEdit

class Animal {

void sound() {
System.out.println("Animal makes sound");

class Dog extends Animal {

void sound() {

System.out.println("Dog barks");

class Test {

public static void main(String[] args) {

Dog d = new Dog();

d.sound(); // Output: Dog barks

What is Dynamic Method Dispatch?

• Dynamic Method Dispatch means calling overridden methods at runtime using a parent class
reference.

• It is also called runtime polymorphism.

It allows Java to decide at runtime which method to run, based on object type.

Example of Dynamic Method Dispatch:

java

CopyEdit

class Animal {

void sound() {

System.out.println("Animal makes sound");

}
class Cat extends Animal {

void sound() {

System.out.println("Cat meows");

class Test {

public static void main(String[] args) {

Animal a; // Reference of parent

a = new Cat(); // Object of child

a.sound(); // Output: Cat meows

Even though reference is of type Animal, it calls Cat's method at runtime.

Important Points for Exam:

Concept Meaning

Method Overriding Same method in parent and child

Dynamic Dispatch Call decided at runtime

Used for Runtime Polymorphis

Question:

Explain various Exception Handling mechanisms in Java.

Answer 1: In Simple English with Examples

What is Exception?

• An exception is an error that occurs during the execution of a program.

• It disrupts the normal flow of the program.

Example: Dividing a number by zero, accessing an invalid array index.


Why use Exception Handling?

• To handle runtime errors.

• To prevent program crash.

• To give meaningful error messages to the user.

Java Exception Handling Keywords:

Keyword Use

try Block where exception might occur

catch Block that handles the exception

finally Block that always runs (for cleanup)

throw Used to throw an exception manually

throws Declares exceptions that a method can throw

1) try and catch:

java

CopyEdit

try {

int a = 10 / 0;

} catch (ArithmeticException e) {

System.out.println("Cannot divide by zero");

2) finally Block:

java

CopyEdit

try {

int arr[] = new int[3];

arr[5] = 10;

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("Invalid index");
} finally {

System.out.println("This block always executes");

3) throw Keyword:

java

CopyEdit

throw new ArithmeticException("Divide by zero error");

4) throws Keyword:

java

CopyEdit

void myMethod() throws IOException {

// code

Extra Theory Points:

• All exceptions are objects of class Exception.

• Java has checked and unchecked exceptions.

• Checked = compile-time (e.g., IOException)

• Unchecked = runtime (e.g., ArithmeticException

Question:

What is the concept of stream? Explain byte stream and character stream in detail.

Answer 1: In Simple English with Theory + Examples

What is a Stream in Java?

• A Stream is a sequence of data.

• It is used to read data (input) or write data (output).

• Java uses streams for handling file operations, network data, etc.

• There are two main types of streams:


1. Byte Stream (for binary data)

2. Character Stream (for text data)

Features of Streams in Java:

• Streams abstract data input/output operations.

• Streams are unidirectional – either input or output.

• Streams use classes from java.io package.

• They are useful for reading/writing files, keyboard input, console output, etc.

1) Byte Stream

• Handles binary data.

• Reads/writes 1 byte at a time.

• Used for non-text files (images, audio, etc.).

Classes Used:

• InputStream (for reading bytes)

• OutputStream (for writing bytes)

Example:

java

CopyEdit

import java.io.*;

public class ByteExample {

public static void main(String[] args) throws Exception {

FileInputStream fin = new FileInputStream("data.txt");

int i;

while((i = fin.read()) != -1) {

System.out.print((char)i);

fin.close();

}
2) Character Stream

• Handles text data (characters, strings).

• Reads/writes 2 bytes at a time (supports Unicode).

• Used for text files.

Classes Used:

• Reader (for reading characters)

• Writer (for writing characters)

Example:

java

CopyEdit

import java.io.*;

public class CharExample {

public static void main(String[] args) throws Exception {

FileWriter fw = new FileWriter("output.txt");

fw.write("Hello Java");

fw.close();

Summary Table:

Stream Type Used For Base Classes Byte Size

Byte Stream Binary Data InputStream / OutputStream 1 byte

Character Stream Text Data Reader / Writer 2 bytes

Question:

What is Inheritance? What are advantages of using inheritance? Show by example the simple inheritance in
Java.

Answer 1: In Simple English

What is Inheritance?
• Inheritance is a feature in Object-Oriented Programming that allows one class (child) to reuse the
properties and methods of another class (parent).

• The extends keyword is used in Java to implement inheritance.

Advantages of Inheritance:

1. Code Reusability – Child class can use methods and variables of the parent class.

2. Improves Maintainability – Common code is written in one place.

3. Supports Method Overriding – Child can modify behavior of parent methods.

4. Extends Functionality – New features can be added without changing existing code.

Example of Simple Inheritance:

java

CopyEdit

// Parent class

class Animal {

void sound() {

System.out.println("Animal makes a sound");

// Child class

class Dog extends Animal {

void bark() {

System.out.println("Dog barks");

// Main class

public class TestInheritance {

public static void main(String[] args) {

Dog d = new Dog();

d.sound(); // method of parent class


d.bark(); // method of child class

Output:

css

CopyEdit

Animal makes a sound

Dog barks

Question:

Explain with example how the access protection is provided for packages in Java? (For 9 Marks)

Answer 1: In Simple English (with Theory + Code)

What is Access Protection?

• In Java, access protection (also called access control) defines how classes and their members
(methods, variables) are accessed within and across packages.

• Java uses access modifiers for access control.

Access Modifiers in Java:

Modifier Same Class Same Package Subclass (another package) Other Package

private Yes No No No

no modifier (default) Yes Yes No No

protected Yes Yes Yes No

public Yes Yes Yes Yes

Package Protection (Default Access):

• If you don’t use any modifier, the class or method has default access.

• Default members are accessible only inside the same package.

Example:
Let’s see how access protection works using two packages: pack1 and pack2.

File 1: pack1/Animal.java

java

CopyEdit

package pack1;

public class Animal {

public void showPublic() {

System.out.println("Public method");

protected void showProtected() {

System.out.println("Protected method");

void showDefault() {

System.out.println("Default method");

private void showPrivate() {

System.out.println("Private method");

File 2: pack2/Test.java

java

CopyEdit

package pack2;

import pack1.Animal;

public class Test extends Animal {

public static void main(String[] args) {


Animal a = new Animal();

a.showPublic(); // Allowed

// a.showProtected(); // Not allowed (through object)

// a.showDefault(); // Not allowed

// a.showPrivate(); // Not allowed

Test t = new Test();

t.showProtected(); // Allowed (inherited)

Output:

pgsql

CopyEdit

Public method

Protected method

Conclusion:

• public – accessible from anywhere

• protected – accessible in same package and subclass

• default – same package only

• private – within same class only

This is how access protection helps in securing Java code across packages.

Question:

What are uncaught exceptions? Illustrate with example the use of try( ), catch( ) and throw( ) methods in
exception handling.

Answer 1: In Simple English

What is an Uncaught Exception?

• An uncaught exception is an error that is not handled using try-catch.

• If not handled, the program crashes or terminates abnormally.


• Example: dividing by zero or accessing null object.

Java Exception Handling Keywords:

Keyword Meaning

try Block of code to test for errors

catch Block that handles the error

throw Used to manually throw an exception

Example: Use of try( ), catch( ), throw( )

java

CopyEdit

public class ExceptionDemo {

// Method to check age

static void checkAge(int age) {

if (age < 18) {

throw new ArithmeticException("Not eligible for voting");

} else {

System.out.println("Eligible for voting");

public static void main(String[] args) {

try {

checkAge(15); // throws exception

} catch (ArithmeticException e) {

System.out.println("Exception caught: " + e.getMessage());

Output:

php
CopyEdit

Exception caught: Not eligible for voting

Question:

Differentiate between character streams and byte streams with examples.

Answer 1: In Simple English (for writing in exam)

Difference between Byte Streams and Character Streams:

Point Byte Stream Character Stream

Data Type Handles binary data (1 byte) Handles character data (2 bytes)

Used For Images, audio, PDF, etc. Text files (letters, symbols)

Classes Used InputStream, OutputStream Reader, Writer

Encoding Does not handle encoding Supports character encoding (like UTF-8)

Speed Faster for binary files Slower but correct for text

Example Classes FileInputStream, FileOutputStream FileReader, FileWriter

Example of Byte Stream:

java

CopyEdit

import java.io.*;

public class ByteExample {

public static void main(String[] args) throws IOException {

FileInputStream in = new FileInputStream("data.bin");

int i;

while((i = in.read()) != -1) {

System.out.print((char)i);

in.close();

}
Example of Character Stream:

java

CopyEdit

import java.io.*;

public class CharExample {

public static void main(String[] args) throws IOException {

FileReader fr = new FileReader("data.txt");

int i;

while((i = fr.read()) != -1) {

System.out.print((char)i);

fr.close();

Question:

State the difference between character and byte stream in Java. Give any two input and any two output
classes for character streams.

Answer 1: In Simple English (for exam)

Difference between Character and Byte Stream:

Point Byte Stream Character Stream

Data Type Handles binary data (1 byte) Handles character data (2 bytes)

Used For Images, videos, PDF, etc. Text files like .txt, .java

Encoding Support No Yes (supports Unicode)

Main Classes InputStream / OutputStream Reader / Writer

Example Class FileInputStream, FileOutputStream FileReader, FileWriter

Two Input Classes of Character Stream:

1. FileReader

2. BufferedReader
Two Output Classes of Character Stream:

1. FileWriter

2. PrintWriter

Question:

Define package and interfaces in Java? Explain it with suitable example.

Answer 1: In Simple English (for exam)

What is a Package in Java?

• A package is a group of related classes and interfaces.

• It helps in organizing code and avoiding name conflicts.

• Example: java.util, java.io, java.lang

Syntax to create package:

java

CopyEdit

package mypack;

Using a class from another package:

java

CopyEdit

import mypack.MyClass;

Example:

java

CopyEdit

// File: MyClass.java

package mypack;

public class MyClass {

public void show() {

System.out.println("Hello from package!");

}
// File: Test.java

import mypack.MyClass;

public class Test {

public static void main(String[] args) {

MyClass obj = new MyClass();

obj.show();

What is an Interface in Java?

• An interface is a blueprint of a class.

• It contains only method declarations (no body).

• A class uses implements keyword to use an interface.

Syntax:

java

CopyEdit

interface Animal {

void sound();

Example:

java

CopyEdit

interface Animal {

void sound(); // abstract method

class Dog implements Animal {

public void sound() {

System.out.println("Dog barks");

}
public class Test {

public static void main(String[] args) {

Dog d = new Dog();

d.sound();

Question:

Elaborate the significance of keyword “super” in Java. Demonstrate with example for super keyword in Java
constructor.

Answer 1: In Simple English (for exam)

What is super in Java?

• super is a keyword in Java used to refer to the parent class (superclass).

• It is mainly used when a child class inherits from a parent class.

Uses of super keyword:

1. To call parent class constructor.

2. To access parent class methods.

3. To access parent class variables.

Use of super in constructor:

When a child class constructor wants to call the constructor of its parent class, it uses super().

Example:

java

CopyEdit

class Animal {

Animal() {

System.out.println("Animal constructor called");

}
class Dog extends Animal {

Dog() {

super(); // calls the constructor of Animal

System.out.println("Dog constructor called");

public class Test {

public static void main(String[] args) {

Dog d = new Dog();

Output:

Animal constructor called

Dog constructor called

Question:

State the importance of finally block. Illustrate how finally block differs from finalize() method.

Answer 1: In Simple English (for exam)

Importance of finally block:

• The finally block in Java is used with try-catch to ensure important code runs no matter what
happens.

• It is used to clean up resources, like closing files, database connections, etc.

• The code in finally always runs:

o If there is no exception

o If an exception is handled

o If an exception is not handled

Syntax:
java

CopyEdit

try {

// risky code

} catch(Exception e) {

// handle error

} finally {

// cleanup code (always runs)

Example:

java

CopyEdit

public class FinallyExample {

public static void main(String[] args) {

try {

int a = 10 / 2;

System.out.println("Result: " + a);

} catch (Exception e) {

System.out.println("Error occurred.");

} finally {

System.out.println("This is finally block.");

Output:

vbnet

CopyEdit

Result: 5

This is finally block.

Difference between finally and finalize():


finally Block finalize() Method

Used for clean-up code after try-catch. Used by Garbage Collector before destroying object.

Runs every time even if exception occurs or not. Called only once by JVM automatically.

Part of exception handling. Part of object cleanup (memory management).

We write it manually. JVM calls it automatically.

Question:

Create a custom Exception class. You need to consider two integer inputs that the user must supply.
You will display the sum of the integers if and only if the sum is less than 100. If it is not less than
100, throw your custom exception.

Answer 1: In Simple English with Code

What is a Custom Exception?

A custom exception is a user-defined class that extends the Exception class to handle specific errors in your
own way.

Steps:

1. Create a class SumTooLargeException that extends Exception.

2. Accept two numbers from the user.

3. If the sum < 100, display it.

4. Else, throw SumTooLargeException.

Code:

java

CopyEdit

import java.util.Scanner;

// Step 1: Create custom exception

class SumTooLargeException extends Exception {

SumTooLargeException(String message) {

super(message);
}

public class CustomExceptionExample {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Step 2: Take input

System.out.print("Enter first number: ");

int a = sc.nextInt();

System.out.print("Enter second number: ");

int b = sc.nextInt();

int sum = a + b;

try {

// Step 3: Check sum condition

if (sum < 100) {

System.out.println("Sum is: " + sum);

} else {

// Step 4: Throw custom exception

throw new SumTooLargeException("Sum is 100 or more, not allowed!");

} catch (SumTooLargeException e) {

System.out.println("Exception: " + e.getMessage());

Sample Output:
Enter first number: 60

Enter second number: 50

Exception: Sum is 100 or more, not allowed!

Question:

Elaborate on the significance of the keyword "final" in Java. With code example of each case.

Answer:

The final keyword in Java is used to make variables, methods, or classes unchangeable or fixed. It helps in
writing secure and reliable code by preventing modification where it's not desired.

1) final Variable

• A variable declared as final cannot be changed once it is initialized.

• It behaves like a constant.

Example:

java

CopyEdit

public class FinalVariableExample {

public static void main(String[] args) {

final int x = 10; // final variable

System.out.println("x = " + x);

// x = 20; // Error! You cannot assign new value to final variable

2) final Method

• A method declared as final cannot be overridden by subclasses.

• This ensures that the implementation of the method remains unchanged.

Example:

java

CopyEdit
class Parent {

final void show() {

System.out.println("Final method from Parent class");

class Child extends Parent {

// void show() { } // Error! Cannot override final method

public class FinalMethodExample {

public static void main(String[] args) {

Child c = new Child();

c.show(); // Calls method from Parent class

3) final Class

• A class declared as final cannot be extended (inherited).

• This prevents any subclass from being created.

Example:

java

CopyEdit

final class Animal {

void sound() {

System.out.println("Animal makes sound");

// class Dog extends Animal { } // Error! Cannot inherit from final class
public class FinalClassExample {

public static void main(String[] args) {

Animal a = new Animal();

a.sound();

Summary:

final used on Effect

Variable Value cannot be changed

Method Method cannot be overridden

Class Class cannot be inherited

Question:

Explain abstract classes and polymorphism in Java with appropriate Java codes.

Answer:

1) Abstract Classes in Java

• An abstract class is a class that cannot be instantiated directly.

• It can have abstract methods (methods without body) that must be implemented by subclasses.

• Abstract classes are used to provide a base template for other classes.

Example of Abstract Class:

java

CopyEdit

abstract class Animal {

abstract void sound(); // abstract method

void sleep() {

System.out.println("Animal is sleeping");
}

class Dog extends Animal {

void sound() {

System.out.println("Dog barks");

public class AbstractClassExample {

public static void main(String[] args) {

Dog d = new Dog();

d.sound(); // Calls Dog's implementation

d.sleep(); // Calls concrete method from Animal

2) Polymorphism in Java

• Polymorphism means many forms.

• It allows a reference variable to refer to objects of different classes that share a common superclass.

• There are two types:

o Compile-time polymorphism (method overloading)

o Runtime polymorphism (method overriding) — we explain runtime here.

Example of Polymorphism using method overriding:

java

CopyEdit

class Animal {

void sound() {

System.out.println("Animal makes a sound");

}
}

class Dog extends Animal {

void sound() {

System.out.println("Dog barks");

class Cat extends Animal {

void sound() {

System.out.println("Cat meows");

public class PolymorphismExample {

public static void main(String[] args) {

Animal a; // Animal reference

a = new Dog();

a.sound(); // Calls Dog's sound()

a = new Cat();

a.sound(); // Calls Cat's sound()

Summary:

Concept Description

Abstract Class Cannot create object, contains abstract methods, provides base for subclasses

Polymorphism One reference variable can refer to multiple types (forms) of objects

You might also like