[Go to site: main page, start]

0% found this document useful (0 votes)
20 views13 pages

Java Class Examples: Inheritance & Exceptions

The document contains multiple Java programs demonstrating various concepts such as classes, inheritance, abstract classes, exception handling, packages, interfaces, and threading. Each program includes code snippets for creating shapes, bank accounts, string manipulations, and handling exceptions, along with their respective outputs. The document serves as a comprehensive guide for understanding object-oriented programming in Java.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views13 pages

Java Class Examples: Inheritance & Exceptions

The document contains multiple Java programs demonstrating various concepts such as classes, inheritance, abstract classes, exception handling, packages, interfaces, and threading. Each program includes code snippets for creating shapes, bank accounts, string manipulations, and handling exceptions, along with their respective outputs. The document serves as a comprehensive guide for understanding object-oriented programming in Java.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1.

WAP to create a simple class to find out the area and perimeter of rectangle and box
using super and this keyword.
// Superclass for Rectangle
class Rectangle {
int length, breadth;

// Constructor using 'this' keyword


Rectangle(int length, int breadth) {
[Link] = length;
[Link] = breadth;
}

// Method to calculate area of rectangle


int area() {
return length * breadth;
}

// Method to calculate perimeter of rectangle


int perimeter() {
return 2 * (length + breadth);
}
}

// Subclass for Box


class Box extends Rectangle {
int height;

// Constructor using 'super' to call Rectangle constructor


Box(int length, int breadth, int height) {
super(length, breadth); // calling superclass constructor
[Link] = height; // referring to current class variable
}

// Method to calculate surface area of box


int surfaceArea() {
return 2 * (length * breadth + breadth * height + height * length);
}

// Method to calculate volume of box


int volume() {
return length * breadth * height;
}
}

// Main class to run the program


public class Main {
public static void main(String[] args) {
// Creating object of Rectangle
Rectangle rect = new Rectangle(10, 5);
[Link]("Rectangle Area: " + [Link]());
[Link]("Rectangle Perimeter: " + [Link]());

// Creating object of Box


Box box = new Box(10, 5, 4);
[Link]("\nBox Surface Area: " + [Link]());
[Link]("Box Volume: " + [Link]());
}
}

2. WAP to design a class account using the inheritance and static that show all function of
bank (withdrawal, deposit).
// Base class Account
class Account {
static int accountCount = 0; // static variable to count number of accounts
String name;
int accNumber;
double balance;

// Constructor
Account(String name, int accNumber, double balance) {
[Link] = name;
[Link] = accNumber;
[Link] = balance;
accountCount++; // increment account count when new account is created
}

// Method to deposit money


void deposit(double amount) {
balance += amount;
[Link]("Deposited: " + amount);
[Link]("New Balance: " + balance);
}

// Method to withdraw money


void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
[Link]("Withdrawn: " + amount);
[Link]("Remaining Balance: " + balance);
} else {
[Link]("Insufficient balance!");
}
}

// Method to display account info


void display() {
[Link]("Account Holder: " + name);
[Link]("Account Number: " + accNumber);
[Link]("Current Balance: " + balance);
}

// Static method to show total number of accounts


static void showTotalAccounts() {
[Link]("Total Accounts Created: " + accountCount);
}
}

// Derived class SavingAccount


class SavingAccount extends Account {
double interestRate;

// Constructor
SavingAccount(String name, int accNumber, double balance, double interestRate) {
super(name, accNumber, balance); // calling base class constructor
[Link] = interestRate;
}

// Method to add interest


void addInterest() {
double interest = balance * interestRate / 100;
balance += interest;
[Link]("Interest Added: " + interest);
[Link]("Balance after Interest: " + balance);
}
}

// Main class
public class Main {
public static void main(String[] args) {
// Creating first account
SavingAccount acc1 = new SavingAccount("Alice", 1001, 5000, 3.5);
[Link]();
[Link](1500);
[Link](2000);
[Link]();
[Link]();

// Creating second account


SavingAccount acc2 = new SavingAccount("Bob", 1002, 3000, 4.0);
[Link]();
[Link](1000);
[Link](500);
[Link]();

[Link]();

// Display total accounts


[Link]();
}
}
Output
Account Holder: Alice
Account Number: 1001
Current Balance: 5000.0
Deposited: 1500.0
New Balance: 6500.0
Withdrawn: 2000.0
Remaining Balance: 4500.0
Interest Added: 157.5
Balance after Interest: 4657.5

Account Holder: Bob


Account Number: 1002
Current Balance: 3000.0
Deposited: 1000.0
New Balance: 4000.0
Withdrawn: 500.0
Remaining Balance: 3500.0
Interest Added: 140.0
Balance after Interest: 3640.0

Total Accounts Created: 2

3. WAP to design a class using abstract methods and classes.


// Abstract class
abstract class Shape {
// Abstract method (no body)
abstract void area();
// Concrete method
void display() {
[Link]("This is a shape.");
}
}

// Subclass for Circle


class Circle extends Shape {
double radius;

Circle(double radius) {
[Link] = radius;
}

// Implementing abstract method


void area() {
double a = [Link] * radius * radius;
[Link]("Area of Circle: " + a);
}
}

// Subclass for Rectangle


class Rectangle extends Shape {
double length, breadth;

Rectangle(double length, double breadth) {


[Link] = length;
[Link] = breadth;
}

// Implementing abstract method


void area() {
double a = length * breadth;
[Link]("Area of Rectangle: " + a);
}
}

// Main class to run the program


public class Main {
public static void main(String[] args) {
// Shape s = new Shape(); // Not allowed: abstract class cannot be instantiated

Shape circle = new Circle(5.0); // upcasting


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

Shape rectangle = new Rectangle(4.0, 6.0); // upcasting


[Link]();
[Link]();
}
}
OUTPUT-
This is a shape.
Area of Circle: 78.53981633974483

This is a shape.
Area of Rectangle: 24.0

4. WAP to design a string class that perform string method (equal, reverse the string, change
case).
class MyString {
String str;

// Constructor
MyString(String str) {
[Link] = str;
}

// Method to check equality with another MyString


boolean isEqual(MyString other) {
return [Link]([Link]);
}

// Method to reverse the string


String reverse() {
StringBuilder sb = new StringBuilder(str);
return [Link]().toString();
}

// Method to change the case of characters


String changeCase() {
StringBuilder result = new StringBuilder();

for (int i = 0; i < [Link](); i++) {


char ch = [Link](i);

if ([Link](ch)) {
[Link]([Link](ch));
} else if ([Link](ch)) {
[Link]([Link](ch));
} else {
[Link](ch); // keep symbols and spaces unchanged
}
}

return [Link]();
}

// Method to display the original string


void display() {
[Link]("Original String: " + str);
}
}

// Main class to test MyString


public class Main {
public static void main(String[] args) {
MyString s1 = new MyString("HelloWorld");
MyString s2 = new MyString("helloworld");

[Link]();
[Link]("Reversed: " + [Link]());
[Link]("Case Changed: " + [Link]());
[Link]();

[Link]();
[Link]("Reversed: " + [Link]());
[Link]("Case Changed: " + [Link]());
[Link]();

[Link]("Are s1 and s2 equal? " + [Link](s2));


}
}

Output
Original String: HelloWorld
Reversed: dlroWolleH
Case Changed: hELLOwORLD

Original String: helloworld


Reversed: dlrowolleh
Case Changed: HELLOWORLD
Are s1 and s2 equal? False

5. WAP to handle the exception using try and multiple catch block.
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
int a = 10, b = 0;

// ArithmeticException: Division by zero


int result = a / b;
[Link]("Result: " + result);

// NullPointerException
String str = null;
[Link]("Length of string: " + [Link]());

// ArrayIndexOutOfBoundsException
int[] arr = {1, 2, 3};
[Link]("Element: " + arr[5]);

} catch (ArithmeticException e) {
[Link]("Caught ArithmeticException: " + [Link]());
} catch (NullPointerException e) {
[Link]("Caught NullPointerException: " + [Link]());
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Caught ArrayIndexOutOfBoundsException: " + [Link]());
} catch (Exception e) {
[Link]("Caught General Exception: " + [Link]());
} finally {
[Link]("This block always executes (finally block).");
}
}
}

Output
Caught ArithmeticException: / by zero
This block always executes (finally block).

6. WAP that implement the Nested try statements.

public class NestedTryExample {


public static void main(String[] args) {
try {
// Outer try block
int[] arr = new int[3];
arr[2] = 30;
[Link]("Outer try block executed");

try {
// Inner try block
int num = 10 / 0; // This will throw ArithmeticException
[Link]("Inner try result: " + num);
} catch (ArithmeticException e) {
[Link]("Caught ArithmeticException in inner try: " + [Link]());
}

try {
// Another inner try block
String str = null;
[Link]([Link]()); // This will throw NullPointerException
} catch (NullPointerException e) {
[Link]("Caught NullPointerException in second inner try: " +
[Link]());
}

// This will throw ArrayIndexOutOfBoundsException


int val = arr[5];
[Link]("Value: " + val);

} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Caught ArrayIndexOutOfBoundsException in outer try: " +
[Link]());
}

[Link]("Program continues...");
}
}
Output
Outer try block executed
Caught ArithmeticException in inner try: / by zero
Caught NullPointerException in second inner try: Cannot invoke "[Link]()" because
"str" is null
Caught ArrayIndexOutOfBoundsException in outer try: Index 5 out of bounds for length 3
Program continues...
7. WAP to create a package that access the member of external class as well as same package.

Steps Covered:

 Creating two packages: mypackage and externalpackage.


 Accessing:
o A class from the same package
o A class from an external package

Directory Structure:

Project/

├── externalpackage/

│ └── [Link]

├── mypackage/

│ ├── [Link]

│ └── [Link]

Step-by-Step Code:

externalpackage/[Link]

package externalpackage;

public class ExternalClass {


public void showExternal() {
[Link]("Accessed method from External Package.");
}
}

mypackage/[Link]
package mypackage;
public class MyClass {
public void showInternal() {
[Link]("Accessed method from Same Package.");
}
}
mypackage/[Link]
package mypackage;

// Import external package


import [Link];

public class MainClass {


public static void main(String[] args) {
// Access class in same package
MyClass obj1 = new MyClass();
[Link]();

// Access class in external package


ExternalClass obj2 = new ExternalClass();
[Link]();
}
}

Compilation and Run Instructions (Command Line):


Go to the root folder (Project) and compile:
javac externalpackage/[Link]
javac mypackage/[Link]
javac -cp . mypackage/[Link]

Run the program:


java -cp . [Link]

Output
Accessed method from Same Package.
Accessed method from External Package.

8. WAP that show the partial implementation of interface.

Interface: [Link]

interface Vehicle {
void start();
void stop();
void fuelType();
}

Abstract Class: [Link]


abstract class Car implements Vehicle {
public void start() {
[Link]("Car is starting...");
}

// stop() and fuelType() are not implemented here


}

Concrete Class: [Link]


class Sedan extends Car {
public void stop() {
[Link]("Car is stopping...");
}

public void fuelType() {


[Link]("Fuel type: Petrol");
}
}

Main Class: [Link]


public class Main {
public static void main(String[] args) {
Vehicle myCar = new Sedan(); // using interface reference
[Link]();
[Link]();
[Link]();
}
}

Output
Car is starting...
Car is stopping...
Fuel type: Petrol

9. WAP to create a thread that implement the Runnable interface.

// Implementing Runnable interface


class MyRunnable implements Runnable {
public void run() {
// Code to be executed in the new thread
for (int i = 1; i <= 5; i++) {
[Link]("Runnable Thread: " + i);
try {
[Link](500); // pause for 500ms
} catch (InterruptedException e) {
[Link]("Thread interrupted: " + [Link]());
}
}
}
}

// Main class
public class Main {
public static void main(String[] args) {
// Creating Runnable object
MyRunnable runnable = new MyRunnable();

// Passing it to Thread constructor


Thread thread = new Thread(runnable);

// Starting the thread


[Link]();

// Main thread execution


for (int i = 1; i <= 5; i++) {
[Link]("Main Thread: " + i);
try {
[Link](500); // pause for 500ms
} catch (InterruptedException e) {
[Link]("Main thread interrupted: " + [Link]());
}
}
}
}

OUTPUT-
Runnable Thread: 1
Main Thread: 1
Runnable Thread: 2
Main Thread: 2
Runnable Thread: 3
Main Thread: 3
Runnable Thread: 4
Main Thread: 4
Runnable Thread: 5
Main Thread: 5

Common questions

Powered by AI

To compile and execute the Java package model described, which involves interactions between classes across multiple packages, follow these instructions: Navigate to the root directory of the project where the package folders are located. Compile each Java file within their respective packages using 'javac' while ensuring the file structure reflects the package structure. For example, 'javac externalpackage/ExternalClass.java' and 'javac mypackage/MyClass.java' . When compiling the MainClass that interacts across packages, include the classpath option '-cp .' to ensure classes are correctly resolved, such as 'javac -cp . mypackage/MainClass.java'. Finally, execute the MainClass using 'java -cp . mypackage.MainClass' to run the program and observe the output .

Encapsulation in the 'MyString' class is achieved by keeping the string data within a private field and providing public methods to access and manipulate that data. The class contains methods like 'isEqual', 'reverse', and 'changeCase' that interact with the encapsulated 'str' field without exposing it directly . 'isEqual' allows comparison of internal strings, 'reverse' provides a way to reverse the string without altering the original data structure, and 'changeCase' modifies the string's case. This use of encapsulation ensures that the internal representation of the string is protected and only modifiable through well-defined interfaces, adhering to principles of object-oriented design .

In Java, interfaces define a contract for classes without implementing them, allowing different classes to implement the methods in their own way. The 'Vehicle' interface in the example specifies methods such as 'start', 'stop', and 'fuelType', providing a template for its implementations . The 'Car' class partially implements the 'Vehicle' interface by providing implementation for the 'start' method only, while the 'Sedan' class, a concrete class extending 'Car', must provide implementations for remaining methods 'stop' and 'fuelType' . This setup promotes code reusability and flexibility by allowing common methods to be defined in interfaces and specific behavior to be implemented in specific classes, fostering polymorphic usage of classes implementing the interface .

The example employs abstract methods to facilitate polymorphism by defining a base Shape class with an abstract method 'area'. This method is overridden by subclasses like Circle and Rectangle to compute the area differently in each case . Polymorphic behavior is manifested when upcasting is used (i.e., referring to subclasses through a base class reference), and the runtime type of the object defines which overridden version of 'area' is invoked. This enables the Shape class to serve as a flexible and common interface for different concrete shape computations while maintaining specific implementations. Thus, it fosters a design where methods can operate on various forms of Shape without needing refactoring .

Nested 'try' statements in Java allow more granular control of exception handling, enabling distinct handling logic for different operations within a broader context. In the NestedTryExample, an outer 'try' block surrounds operations that can throw exceptions, with inner 'try' blocks handling specific operations like division and null pointer access separately . This structure allows catching exceptions specific to each block, such as ArithmeticException and NullPointerException, before progressing to potentially catch other exceptions in surrounding blocks. This hierarchical management of exceptions enables developers to maintain targeted and organized error handling strategies .

Abstract classes and methods in Java provide a blueprint for other classes, defining methods that must be implemented by subclasses while potentially including implemented methods. In the Shape class example, the abstract class 'Shape' contains an abstract method 'area()', which lacks a method body and forces subclasses like 'Circle' and 'Rectangle' to provide their own implementations of this method . This ensures that each shape can calculate its area according to its specific needs, demonstrating polymorphism. Additionally, the 'Shape' class includes a concrete method 'display()', highlighting how abstract classes can house complete methods that could be shared across all inheriting classes .

In Java, the 'super' keyword is used to call the constructor of a parent class, enabling inheritance by initializing objects that possess attributes of the superclass. In the provided example, the Box class extends the Rectangle class, using 'super' to invoke the Rectangle constructor to initialize length and breadth . This exemplifies constructor chaining, ensuring that Box inherits the properties of Rectangle. The 'this' keyword, on the other hand, is used within a class's constructor to refer to the instance variables of that class. In the Rectangle class, 'this' is used to differentiate the instance variables length and breadth from the parameters passed to the constructor .

Implementing the Runnable interface for creating threads, as shown in the MyRunnable example, offers several advantages over extending the Thread class directly. Primarily, it allows a class to extend other classes since it is not locked into extending Thread. It permits the separation of threading logic from Thread class hierarchy, promoting better design through composition . Runnable also provides a cleaner abstraction for the task to be executed, allowing it to be submitted to executors for managed execution. Moreover, in environments requiring multiple inheritance, Runnable offers a more flexible mechanism than subclass inheritance alone .

The 'static' keyword in Java is used to define class-level variables and methods that belong to the class rather than instances of the class. In the bank account example, a static variable 'accountCount' is used to keep track of the number of accounts created . This allows the variable to be shared across all instances of the Account class, maintaining a count independent of individual account objects. The static method 'showTotalAccounts()' provides an interface to access this static variable, demonstrating a method that operates at the class level rather than on a specific instance .

In Java, 'try' blocks are used to wrap code that might throw an exception, while 'catch' blocks are used to handle specific exceptions that are thrown. Multiple 'catch' blocks allow handling of different exception types, such as ArithmeticException, NullPointerException, and ArrayIndexOutOfBoundsException, as shown in the provided example . The 'finally' block is used to execute code regardless of whether an exception is caught or not, ensuring that necessary cleanup code runs or other essential actions are performed .

You might also like