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

Java QB ANS

The document explains key concepts in Java, including the use of the super keyword in inheritance, how interfaces enable multiple inheritance, and the definition of abstract classes and methods. It also covers exception handling, including key terms and the creation of custom exceptions, as well as the concept of importing packages. Additionally, it discusses nested try blocks and the use of interfaces with examples demonstrating their implementation.

Uploaded by

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

Java QB ANS

The document explains key concepts in Java, including the use of the super keyword in inheritance, how interfaces enable multiple inheritance, and the definition of abstract classes and methods. It also covers exception handling, including key terms and the creation of custom exceptions, as well as the concept of importing packages. Additionally, it discusses nested try blocks and the use of interfaces with examples demonstrating their implementation.

Uploaded by

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

Module 3

1) What is the importance of super keyword in inheritance? Give example.


A)
In object-oriented programming, the super keyword is used within a subclass to refer to
the superclass (or parent class). It's particularly important for the following reasons:
1. Accessing Superclass Methods: When you override a method in a subclass, you can
call the superclass's version of the method using super. This is useful when you want
to add to, rather than completely replace, the functionality of the superclass method.
2. Calling Superclass Constructors: A subclass can call a constructor of its superclass
using super. This ensures that the superclass's state is initialized before the subclass's
state, which is crucial for proper inheritance behavior.
class Parent {
void display() {
System.out.println("This is the display method of the Parent class.");
}
}

class Child extends Parent {


void display() {
super.display(); // Calling the display method of the Parent class
System.out.println("This is the display method of the Child class.");
}
}

public class SimpleExample {


public static void main(String[] args) {
Child child = new Child();
child.display();
}
}
2) Explain how interface is used to achieve multiple inheritance in java.
In Java, multiple inheritance (where a class inherits from more than one parent class) is
not supported directly due to the "diamond problem" and complexity it introduces.
However, Java provides a way to achieve multiple inheritance of type through interfaces.
Interfaces allow a class to inherit behavior from multiple sources.
How it Works
1. Interfaces Definition: An interface defines a contract (a set of methods) that a class
must implement. It cannot provide implementation details, just method signatures.
2. Implementing Interfaces: A class can implement multiple interfaces, thereby
inheriting the method signatures from all the interfaces it implements.
Example:
interface Animal {
void makeSound();
}
interface Pet {
void play();
}
class Dog implements Animal, Pet {
@Override
public void makeSound() {
System.out.println("Bark");
}
@Override
public void play() {
System.out.println("The dog is playing.");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.makeSound();
myDog.play();
}
}
1. Interface Definitions: We have two interfaces, Animal and Pet, each with a single
method.
2. Class Implementation: The Dog class implements both Animal and Pet interfaces and
provides concrete implementations for the methods declared in these interfaces.
3. Main Method: In the main method, we create an instance of Dog and call the
methods from both Animal and Pet interfaces, demonstrating that Dog inherits behavior
from both interfaces.

3) What is abstract class and abstract method? Explain with example.


A)
Abstract Class
An abstract class serves as a blueprint for other classes. It can contain both abstract
methods and concrete methods.
Abstract Method
An abstract method is a method that is declared without an implementation. Subclasses
are required to provide the implementation for these methods.
Example:
// Abstract class
abstract class Animal {
abstract void makeSound(); // Abstract method
}
// Dog class extending Animal
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Bark");
}
}
// Cat class extending Animal
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Meow");
}
}
// Main class to test the implementation
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();

myDog.makeSound(); // Bark
myCat.makeSound(); // Meow
}
}

4) Define an exception. What are the key terms used in exception handling?
Explain
A)
Exception: An exception is an event that occurs during the execution of a program that
disrupts the normal flow of instructions. It is a way to signal error conditions and handle
them in a controlled manner. Exceptions can be caused by various factors such as invalid
user input, device failure, or programming errors.
Key Terms in Exception Handling:

• Try
• Catch
• Finally
• Throw
• Throws
try Block:
• The try block contains the code that might cause an exception (divide(10, 0)).
catch Block:
• The catch block catches and handles the ArithmeticException.
finally Block:
• The finally block contains code that will always be executed, regardless of whether an
exception was thrown or caught.
throw Statement:
• The divide method uses the throw statement to throw an ArithmeticException when
division by zero is attempted.
throws Keyword:
• The divide method declares that it can throw an ArithmeticException using the
throws keyword.
Example:
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
int result = divide(10, 0); // This will cause an ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e);
} finally {
System.out.println("Finally block executed.");
}
}
public static int divide(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException("Division by zero");
} return a / b;
}
Module 5
1 .Explain the concept of importing packages in java and provide an
example demonstrating the usage of the import statement
A)
Concept of Importing Packages
• Default Package: Java automatically imports the java.lang package by default, which
includes fundamental classes such as String, System, and Math. For other packages,
you need to use the import statement.
• Single Type Import: You can import a specific class or interface from a package.
import packageName.ClassName;
• On-Demand Import: You can import all the classes and interfaces from a package.
import packageName.*;
Example

// File 1 // File:2
package com.example.utility; Main.java
public class MathUtils { import com.example.utility.MathUtils;
public static int add(int a, int b) {
return a + b; public class Main {
} public static void main(String[] args) {
} int sum = MathUtils.add(10, 20);
System.out.println("Sum: " + sum);
}
}

Benefits of Using Packages


• Organizational: Packages help organize classes and interfaces into a structured
hierarchy.
• Modularity: They promote modularity by grouping related functionality.
• Reusability: Code can be reused across different projects by importing the necessary
packages.
• Avoid Naming Conflicts: Packages prevent naming conflicts by providing a
namespace for classes and interfaces.
2) How do you create your own exception class? Explain with a program
A)
Steps to Create Your Own Exception Class
1. Extend the Exception Class: Your custom exception should extend either
Exception (for checked exceptions) or RuntimeException (for unchecked
exceptions).
2. Constructor Definitions: Define constructors in your custom exception
class. Typically, you'll include constructors that accept a message and a
cause.
public class Main {
// Custom Exception Class
static class DivisionByZeroException extends Exception {
public DivisionByZeroException(String message) {
super(message);
}
}
// Main method
public static void main(String[] args) {
try {
int result = divide(10, 0); // This will throw the custom exception
System.out.println("Result: " + result);
} catch (DivisionByZeroException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}

// Method to perform division


public static int divide(int a, int b) throws DivisionByZeroException {
if (b == 0) {
throw new DivisionByZeroException("Cannot divide by zero.");
}
return a / b;
}
}

3) Demonstrate the working of a nested try block with an


example.
A)
Nested try blocks are try blocks within other try blocks. They can be useful
for handling exceptions that might occur in a specific part of a larger block
of code.
Example:
public class NestedTryExample {
public static void main(String[] args) {
try {
// Outer try block
try {
int[] arr = {1, 2, 3};
System.out.println(arr[3]); // This will throw
ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds: " + e.getMessage());
}
// Inner try block
try {
int result = 10 / 0; // This will throw ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero: " + e.getMessage());
}
} catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
}
}
}

4)Discuss use of interface. Give its syntax with example in java.


A)
Interfaces in Java are used to define a contract that a class can implement. They are a
powerful tool for achieving abstraction and multiple inheritance of type. Interfaces specify
what a class must do, but not how it does it, allowing different classes to implement the
same set of methods in diverse ways.
1. Abstraction: Interfaces allow you to define methods that must be implemented by a
class, without specifying how they should be implemented.
2. Multiple Inheritance: Java doesn't allow a class to inherit from more than one class.
However, a class can implement multiple interfaces.
3. Loose Coupling: By using interfaces, you can change the implementation of a class
without affecting the code that uses the interface.
Example:
// Interface Definition
interface Vehicle {
void start(); // Abstract method
void stop(); // Abstract method
}
// Class that implements Vehicle interface
class Car implements Vehicle {
public void start() {
System.out.println("Car is starting");
}

public void stop() {


System.out.println("Car is stopping");
}
}
// Another class that implements Vehicle interface
class Bike implements Vehicle {
public void start() {
System.out.println("Bike is starting");
}
public void stop() {
System.out.println("Bike is stopping");
}
}
// Main class to test the implementation
public class Main {
public static void main(String[] args) {
Vehicle myCar = new Car();
Vehicle myBike = new Bike();

myCar.start(); // Output: Car is starting


myCar.stop(); // Output: Car is stopping

myBike.start(); // Output: Bike is starting


myBike.stop(); // Output: Bike is stopping
}
}

You might also like