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

java assignment 2 ans another pdf

The document discusses various forms of inheritance in Java, including single, multilevel, hierarchical, multiple, and hybrid inheritance, with examples provided for single inheritance and the use of the super keyword. It also explains abstract and final keywords, method overriding, dynamic method dispatching, and how to achieve multiple inheritance through interfaces. Additionally, it covers package creation, access modifiers, exception handling, and built-in exception classes in Java with relevant examples.

Uploaded by

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

java assignment 2 ans another pdf

The document discusses various forms of inheritance in Java, including single, multilevel, hierarchical, multiple, and hybrid inheritance, with examples provided for single inheritance and the use of the super keyword. It also explains abstract and final keywords, method overriding, dynamic method dispatching, and how to achieve multiple inheritance through interfaces. Additionally, it covers package creation, access modifiers, exception handling, and built-in exception classes in Java with relevant examples.

Uploaded by

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

1.

Discuss the various forms of inheritance and provide a sample program to illustrate the
concept of single inheritance

Inheritance is a mechanism in object-oriented programming that allows a class (called the


child or derived class) to inherit properties and methods from another class (called the
parent or base class). This promotes code reusability and hierarchical classification.

Forms of Inheritance

1. Single Inheritance
A class inherits from a single parent class.
Example: Class B inherits from Class A.

2. Multilevel Inheritance
A class inherits from a class, which in turn inherits from another class.
Example: Class C inherits from Class B, which inherits from Class A.

3. Hierarchical Inheritance
Multiple classes inherit from a single parent class.
Example: Classes B, C, and D inherit from Class A.

4. Multiple Inheritance (Not directly supported in Java due to the "Diamond Problem")
A class inherits from multiple parent classes. This is achieved in Java using interfaces.

5. Hybrid Inheritance
A combination of two or more types of inheritance. Java handles this through interfaces.

---

Example of Single Inheritance in Java

class Animal {
String name = "Animal";

void display() {
System.out.println("I am an " + name);
}
}

class Dog extends Animal {


String breed = "Labrador";

void showBreed() {
System.out.println("I am a " + breed);
}
}

public class SingleInheritance {


public static void main(String[] args) {
Dog myDog = new Dog();
myDog.display(); myDog.showBreed();
}
}

3. Explain the application of the super keyword in Java with a relevant example.

The super keyword in Java is a reference variable used to access members of the parent
class. It is particularly useful in inheritance to avoid ambiguity when the child class overrides
methods or has variables with the same name as the parent class.

Applications of super Keyword

1. Accessing Parent Class Variables


Used when the child class has a variable with the same name as the parent class.

2. Calling Parent Class Methods


Used when the child class overrides a method from the parent class but needs to call the
parent class's version of the method.

3. Calling Parent Class Constructor


Used to call the constructor of the parent class from the child class. This must be the first
statement in the child class constructor.

Example:
class Animal {
String name = "Animal";

void sound() {
System.out.println("Animals make sound");
}
}

class Dog extends Animal {


String name = "Dog";

void sound() {
super.sound();
System.out.println("Dogs bark");
}

void displayNames() {
System.out.println("Parent name: " + super.name);
System.out.println("Child name: " + name);
}
}

public class SuperExample {


public static void main(String[] args) {
Dog myDog = new Dog();
myDog.sound(); myDog.displayNames();
}
}

4. Explain abstract and final keyword with an example.

Abstract Keyword

The abstract keyword in Java is used to declare a class or method as incomplete:

1. Abstract Class:

Cannot be instantiated.

May have both abstract methods (methods without implementation) and concrete methods
(methods with implementation).

2. Abstract Method:

Does not have a body and must be overridden in the subclass.

Final Keyword

The final keyword is used to declare constants, methods, or classes that cannot be modified:

1. Final Variable:

Cannot be reassigned after initialization.


2. Final Method:

Cannot be overridden by subclasses.

3. Final Class:

Cannot be extended (no subclasses can be created).

---

Example Program

abstract class Animal {


abstract void sound();
void eat() { System.out.println("Animals eat food.");
}
}

final class Dog extends Animal {


void sound() {
System.out.println("Dogs bark.");
}
}

public class AbstractAndFinalExample {


public static void main(String[] args) {
Dog myDog = new Dog(); myDog.sound();
myDog.eat();
}
}

5. Explain method overriding and dynamic method dispatching in java with example .

Method Overriding in Java

Method overriding occurs when a subclass provides a specific implementation for a method
already defined in its parent class.

The method in the child class must have the same name, return type, and parameters as the
method in the parent class.
It allows runtime polymorphism.

---

Dynamic Method Dispatching in Java

Dynamic method dispatch (or runtime polymorphism) is the process where the method to be
executed is determined at runtime based on the object type, not the reference type.

This is achieved using method overriding and enables flexibility by allowing behavior to be
defined based on the actual object being referred to.

---

Example Program

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

class Dog extends Animal {


void sound() {
System.out.println("Dog barks.");
}
}

public class MethodOverridingExample {


public static void main(String[] args) {
Animal myAnimal;
myAnimal = new Animal(); myAnimal.sound();
myAnimal = new Dog(); myAnimal.sound();
}
}

7. How do you achieve multiple inheritance in java explain with an example.

Multiple Inheritance in Java

Java does not support multiple inheritance directly for classes (i.e., a class cannot inherit
from more than one class) due to the diamond problem. However, you can achieve multiple
inheritance in Java through interfaces. A class can implement multiple interfaces, allowing it
to inherit behavior from multiple sources.
How to Achieve Multiple Inheritance in Java

Using Interfaces: A class can implement multiple interfaces, each providing a set of methods
that the class must implement. This achieves the effect of multiple inheritance.

---

Example Program Using Interfaces for Multiple Inheritance

interface Animal {
void sound();
}

interface Mammal {
void habitat();
}

class Dog implements Animal, Mammal {


public void sound() {
System.out.println("Dog barks.");
}
public void habitat() {
System.out.println("Dogs live on land.");
}
}

public class MultipleInheritanceExample {


public static void main(String[] args) {
Dog myDog = new Dog();
myDog.sound();
myDog.habitat();
}
}

8. Define package. Explain the steps involved in creating a user-defined package with an
example.

Package in Java

A package in Java is a way to group related classes and interfaces together. It helps in
organizing the code and avoids name conflicts. Packages also make it easier to manage and
maintain large software projects. Java provides two types of packages:

1. Built-in Packages: Predefined in Java (e.g., java.util, java.io).


2. User-defined Packages: Created by the programmer to group their own classes and
interfaces.

Steps to Create a User-Defined Package

1. Create a Package: Use the package keyword to declare a package.

2. Create Classes in the Package: Define the classes or interfaces that will be part of the
package.

3. Compile the Classes: Compile the classes, and the .class files will be created in a folder
named after the package.

4. Access the Package in Another Class: Use the import statement to access the classes
from the user-defined package.

Example of Creating and Using a User-Defined Package

Step 1: Create a Package

Let's create a package named mypackage with a class HelloWorld.

File: HelloWorld.java

package mypackage; public class HelloWorld {


public void displayMessage() {
System.out.println("Hello from my custom package!");
}
}

Step 2: Create a Class to Access the Package

Now, we create another class outside the package to access the HelloWorld class.

File: TestPackage.java

import mypackage.HelloWorld;
public class TestPackage {
public static void main(String[] args) {
HelloWorld obj = new HelloWorld(); obj.displayMessage();
}
}

Step 3: Compile and Run

1. Compile the HelloWorld class:

javac HelloWorld.java

This will create a HelloWorld.class file in the mypackage directory.

2. Compile the TestPackage class:

javac TestPackage.java

3. Run the TestPackage class:

java TestPackage

9. Examine the various levels of access protections available for packages and their
implications
with suitable example.

Access Modifiers in Java

Java provides several levels of access protection that determine the visibility and
accessibility of classes, methods, and variables across different packages. The four primary
access levels are:

1. public:

The member is accessible from anywhere, both inside and outside the package.

2. protected:

The member is accessible within the same package and by subclasses (including
subclasses in different packages).

3. default (no modifier):

The member is accessible only within the same package (package-private).


4. private:

The member is accessible only within the same class.

---

Implications of Access Modifiers

public:

The member is universally accessible.

protected:

The member can be accessed by classes within the same package and subclasses in any
package.

default:

The member is accessible only within classes in the same package.

private:

The member is restricted to the class in which it is defined.

Example:
// File: AccessExample.java

public class AccessExample {


public String publicVar = "Public Variable";
protected String protectedVar = "Protected Variable";
String defaultVar = "Default Variable";
private String privateVar = "Private Variable";
public void displayPublic() {
System.out.println(publicVar);
}

protected void displayProtected() {


System.out.println(protectedVar);
}
void displayDefault() {
System.out.println(defaultVar);
}

private void displayPrivate() {


System.out.println(privateVar);
}
}

// File: TestAccess.java

public class TestAccess {


public static void main(String[] args) {
AccessExample obj = new AccessExample();
System.out.println(obj.publicVar); obj.displayPublic();
System.out.println(obj.protectedVar); obj.displayProtected();
System.out.println(obj.defaultVar); obj.displayDefault();
System.out.println(obj.privateVar); obj.displayPrivate();
}
}

11. Explain multiple catch block in java with an example

Multiple Catch Blocks in Java

In Java, you can use multiple catch blocks to handle different types of exceptions. This
allows you to catch and handle multiple exceptions that might arise from a single try block.

You can have multiple catch blocks following a single try block, each catching a different type
of exception.

Each catch block should be specific to the type of exception it handles.

Java will execute the first matching catch block and skip the rest.

Example Program

public class MultipleCatchExample {


public static void main(String[] args) {
try {
int result = 10 / 0;
String str = null;
System.out.println(str.length());
}
catch (ArithmeticException e) {
System.out.println("Error: Division by zero.");
}
catch (NullPointerException e) {
System.out.println("Error: Null pointer exception.");
}
catch (Exception e) {
System.out.println("General error: " + e);
}
}
}

15. Describe how a divide-by-zero error can be managed in Java, providing an example

Handling Divide-by-Zero Error in Java

In Java, a divide-by-zero error can occur when you attempt to divide a number by zero. This
typically results in an ArithmeticException. To handle this error, you can use a try-catch block
to catch and manage the exception gracefully.

If an integer is divided by zero, Java throws an ArithmeticException.

For floating-point numbers (float or double), dividing by zero does not throw an exception;
instead, it results in Infinity or NaN (Not a Number).

Example Program to Handle Divide-by-Zero

public class DivideByZeroExample {


public static void main(String[] args) {
int numerator = 10;
int denominator = 0;

try {
int result = numerator / denominator;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
}
}
}

16. Explain Built in Exception classes in java with an example program.

Built-in Exception Classes in Java

Java provides several built-in exception classes to handle different types of errors and
abnormal situations that may occur during the execution of a program. These exception
classes are part of the java.lang package. Some commonly used built-in exception classes
include:
1. ArithmeticException: Thrown when an arithmetic error occurs, such as dividing by zero.

2. NullPointerException: Thrown when trying to access a method or member of a null object.

3. ArrayIndexOutOfBoundsException: Thrown when trying to access an array element with


an invalid index.

4. NumberFormatException: Thrown when trying to convert a string to a number and the


string format is invalid.

5. ClassCastException: Thrown when trying to cast an object to a type that it is not


compatible with.

6. IOException: Thrown when an input or output operation fails.

Example:
public class SimpleExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
}
try {
String str = null;
System.out.println(str.length());
}
catch (NullPointerException e) {
System.out.println("Error: Null pointer exception.");
}
}
}

You might also like