0% found this document useful (0 votes)
12 views

Kunal Java Unit-2

Uploaded by

manglamdubey2011
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Kunal Java Unit-2

Uploaded by

manglamdubey2011
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Index:

1. Define inheritance in OOP. What are the its advantages?

2. What is ‘super’ keyword in java? What are its purposes?

3. Explain method overriding in Java.

4. Write a java program where we import package and

subpackage.

5. Explain checked and unchecked exception.

6. Explain exception handling in java using “try”, “catch”

and “finally” block.


1. Define inheritance in OOP. What are the its advantages?
ANS-
Inheritance: A mechanism wherein a new class inherits the properties (fields) and
behaviors (methods) of an existing class. This allows the new class to reuse, extend,
or modify the functionality defined in the base class.

// Base class
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}

// Derived class
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Inherited method
dog.bark(); // Method of Dog class
}
}

Advantages:
Reuse code: You don't have to start from scratch. You can use parts of the original
blueprint (like the walls and roof) for all your houses.
Easier to change: If you decide to improve the roof design, you only need to
change it once in the original blueprint. All your houses will have the better roof.
Add new things: You can add extra rooms or a pool to a specific house without
changing the basic blueprint.
Organize things: You can group similar houses together (like all the big houses)
to make it easier to find what you need.
Hide details: You can keep the details of how the walls are built hidden, so you
only need to worry about the overall design of the house.
2. What is ‘super’ keyword in java? What are its purposes?
ANS- The super keyword in Java is used to refer to the immediate parent class of the
current object. It serves 2 main purposes in inheritance, calling superclass
constructors and accessing superclass methods and variables.
Calling Superclass Constructor
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 Main {


public static void main(String[] args) {
Dog dog = new Dog();
}
}
Accessing Superclass Methods
class Animal {
void eat() {
System.out.println("Animal eats");
}
}

class Dog extends Animal {


void eat() {
super.eat(); // Calls the eat method of Animal
System.out.println("Dog eats");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
}
}
3. Explain method overriding in Java.
ANS-
You have a parent class with a method.
A child class wants to do something different when that method is called.
So, it creates a new version of the method with the same name and ingredients
(parameters).
// Superclass
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
// Subclass
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Dog(); // Upcasting
myAnimal.makeSound(); } } // Calls the overridden method in Dog
4. Write a java program where we import package and subpackage.
ANS-
Program of importing package “com.example” with subpackage “utilites”
Directory Structure:
src
└── com
└── example
├── MainProgram.java
└── utilities
└── Helper.java
subpackage
package com.example.utilities;
public class Helper {
public static void displayMessage() {
System.out.println("Hello from Helper class!");
}
}
package
package com.example;
import com.example.utilities.Helper;
public class MainProgram {
public static void main(String[] args) {
Helper.displayMessage(); // Using method from the imported Helper class } }
5. Explain checked and unchecked exception.
ANS-
Checked Exceptions:

• Checked exceptions are exceptions that the compiler forces you to either handle
using a try-catch block

• Or declare in the method signature using the throws keyword.


Examples include: IO exception, SQL exception.
import java.io.*;
public class CheckedExceptionExample {
public static void main(String[] args) {
try {
FileReader file = new FileReader("file.txt");
BufferedReader fileInput = new BufferedReader(file);

// Read a line from the file


String line = fileInput.readLine();
System.out.println(line);
fileInput.close();
} catch (IOException e) {
System.out.println("Exception occurred: " + e);
}
}
}
Unchecked Exceptions:

• Unchecked exceptions, also known as runtime exceptions.

• They usually occur due to programming bugs or logical errors and can be
avoided with proper coding practices.
Examples include: NullPointerException, ArrayIndexOutOfBoundsException,
ArithmeticException.
public class UncheckedExceptionExample {
public static void main(String[] args) {
int num = 10;
int result = num / 0; // ArithmeticException occurs here
System.out.println(result);
}
}
6. Explain exception handling in java using “try”, “catch” and “finally” block.
ANS- Exception handling in Java allows you to deal with unexpected or exceptional
situations that may occur during the execution of a program.
• try block: Contains the code where an exception might occur.
• catch block: Catches the exception thrown in the try block.
• finally block: Optional block it's used to perform cleanup actions (closing files,
releasing resources, etc.).
import java.io.*;
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
// Code where an exception might occur
int result = 10 / 0; // ArithmeticException: Division by zero
} catch (ArithmeticException e) {
// Catch block handling the exception
System.out.println("ArithmeticException caught: " + e.getMessage());
} finally {
// Finally block for cleanup or final operations
System.out.println("Finally block executed");
}
}
}
7. Differentiate bw throw and throws.
ANS-

Aspect throw throws

Purpose Used to manually throw an Used to declare exceptions that might


exception. be occur.

Keyword throw new void methodName() throws


Usage SomeException(); SomeException {...}

Applied To Used inside a method. Used in method signature.

Handling Raises a specific exception Informs the caller about potential


in the code. exceptions.

Mechanism Throws an exception object Declares that the method may throw
explicitly. certain exceptions.

Impact on Stops the normal flow of Doesn't affect the method's actual
Flow execution. execution; used for notification.

You might also like