OOP Java
OOP Java
1. **What is a constructor? What are its 3. **Describe the use of `throw` 5. **What do you mean by 6. **Why is Java a robust programming
special properties?** keyword.** encapsulation?** language?**
- **Definition:** A constructor is a special - **Definition:** The `throw` keyword in - **Definition:** Encapsulation is the - **Definition:** Java is considered robust
method in a class used to initialize objects. Java is used to explicitly throw an exception concept of wrapping data (variables) and because of its strong memory management,
It is called when an instance of the class is from a method or a block of code. It is methods (code) together as a single unit. In the absence of pointers which reduces the
created. typically used to signal an error condition Java, it is achieved by making the class chance of memory corruption, automatic
- **Special Properties:** that needs to be handled by the calling fields private and providing public getter garbage collection, exception handling
- It has the same name as the class. method or a higher level of the application. and setter methods to access and modify mechanisms, and strict type-checking at
- It has no return type, not even `void`. the fields. compile time and runtime.
- It is automatically called when an **Example:**
object is created. ```java **Example:** **Example:**
- It can be overloaded to create multiple public class TestThrow { ```java ```java
constructors with different parameters. static void checkAge(int age) { public class Person { public class TestRobustness {
if (age < 18) { private String name; public static void main(String[] args) {
**Example:** throw new private int age; try {
```java ArithmeticException("Access denied - You int[] arr = new int[5];
public class Example { must be at least 18 years old."); // Getter method for name arr[10] = 50; // This will throw an
int x; } else { public String getName() { ArrayIndexOutOfBoundsException
System.out.println("Access return name; } catch
// Constructor granted - You are old enough!"); } (ArrayIndexOutOfBoundsException e) {
public Example(int y) { } System.out.println("Exception
x = y; } // Setter method for name caught: " + e);
} public void setName(String newName) }
public static void main(String[] args) { { }
public static void main(String[] args) { checkAge(15); // Throws an name = newName; }
Example obj = new Example(5); exception } ```
System.out.println(obj.x); // Outputs: }
5 } // Getter method for age —-------------------------------------------
} public int getAge() { 7. **Explain the following points:**
} —------------------------------- return age; - **JVM (Java Virtual Machine):** A
``` 4. **What do you mean by the } virtual machine that runs Java bytecode. It
—----------------------------------------- package?** makes Java platform-independent by
- **Definition:** A package in Java is a // Setter method for age abstracting the underlying operating
namespace that groups related classes and public void setAge(int newAge) { system.
interfaces. It helps organize code and age = newAge; - **JRE (Java Runtime Environment):**
prevent naming conflicts. Packages also } Provides libraries, the JVM, and other
provide access protection and can make it } components to run Java applications. It
easier to locate and use classes. does not include development tools like
public class TestEncapsulation { compilers.
**Example:** public static void main(String[] args) { - **JDK (Java Development Kit):** A
```java Person p = new Person(); full-featured software development kit for
package com.example.myapp; p.setName("John"); Java, which includes the JRE, compilers,
p.setAge(30); and tools like JavaDoc and Java Debugger.
public class MyClass { System.out.println("Name: " + - **Bytecode:** An intermediate code
public void display() { p.getName()); // Outputs: Name: John generated by the Java compiler, which the
System.out.println("Hello from System.out.println("Age: " + JVM interprets and executes. Bytecode is
MyClass"); p.getAge()); // Outputs: Age: 30 platform-independent.
} } - **Abstraction:** The concept of hiding
} } complex implementation details and
``` exposing only the necessary and relevant
// To use this class: —------------------------------------------ parts of an object. Achieved using abstract
import com.example.myapp.MyClass; classes and interfaces.
8. **What do you understand by wrapper - **Platform Independent:** Java
public class TestPackage { class?** programs can run on any device or
public static void main(String[] args) { - **Definition:** Wrapper classes provide a way operating system that has a compatible
MyClass obj = new MyClass(); to use primitive data types (like `int`, `char`, JVM, making Java truly cross-platform.
obj.display(); // Outputs: Hello from `double`) as objects. Each primitive type has a
MyClass corresponding wrapper class (e.g., `Integer`, **Example:**
`Character`, `Double`).
} ```java
} abstract class Animal {
``` **Example:** abstract void makeSound();
—--------------------------- ```java }
public class TestWrapperClass {
public static void main(String[] args) { class Dog extends Animal {
int x = 5; // primitive type void makeSound() {
Integer y = new Integer(x); System.out.println("Woof");
Integer z = x; }
}
// Unboxing
int a = y; public class TestAbstraction {
public static void main(String[] args) {
System.out.println("Integer y: " + y); Animal a = new Dog();
// Outputs: Integer y: 5 a.makeSound(); // Outputs: Woof
System.out.println("Integer z: " + z); }
// Outputs: Integer z: 5 }
9. **What do you understand by Garbage System.out.println("int a: " + a); //
Collection?** Outputs: int a: 5 }}
2. **What is polymorphism?** - **Definition:** Garbage Collection in 11. **What do you mean by abstract 13. **How can we create a thread?**
- **Definition:** Polymorphism is the Java is the process by which the JVM class?** - **Definition:** In Java, a thread can be
ability of a single interface or method to automatically removes objects that are no - **Definition:** An abstract class in Java created in two ways: by extending the
operate in different ways depending on the longer in use or reachable, freeing up is a class that cannot be instantiated `Thread` class and overriding its `run`
type of object it is acting upon. It allows one memory resources. directly. It can contain abstract methods method, or by implementing the `Runnable`
interface to be used for a general class of (methods without a body) that must be interface and passing an instance of the
actions. **Example:** implemented by its subclasses, as well as implementing class to a `Thread` object.
- **Types:** ```java concrete methods (methods with a body).
- **Compile-time polymorphism (Method public class TestGarbageCollection { **Example 1: Extending Thread class**
Overloading):** Multiple methods with the public static void main(String[] args) { **Example:** ```java
same name but different parameters. TestGarbageCollection t1 = new ```java class MyThread extends Thread {
- **Runtime polymorphism (Method TestGarbageCollection(); abstract class Animal { public void run() {
Overriding):** A subclass provides a TestGarbageCollection t2 = new abstract void makeSound(); System.out.println("Thread is
specific implementation of a method that is TestGarbageCollection(); running");
already defined in its superclass. void sleep() { }
t1 = null; // Eligible for garbage System.out.println("This animal
**Example:** collection sleeps"); public static void main(String[] args) {
```java t2 = null; // Eligible for garbage } MyThread t1 = new MyThread();
class Animal { collection } t1.start();
void makeSound() { }
System.out.println("Animal makes a System.gc(); // Requesting JVM to class Dog extends Animal { }
sound"); run Garbage Collector void makeSound() { ```
} } System.out.println("Woof");
} } **Example 2: Implementing Runnable
@Override } interface**
class Dog extends Animal { protected void finalize() { ```java
@Override System.out.println("Garbage public class TestAbstractClass { class MyRunnable implements Runnable
void makeSound() { collector called"); public static void main(String[] args) { {
System.out.println("Dog barks"); } Animal a = new Dog(); public void run() {
} } a.makeSound(); // Outputs: Woof System.out.println("Thread is
} —------------------------------------------ a.sleep(); // Outputs: This animal running");
10. **What is inheritance?** sleeps }
class Cat extends Animal { - **Definition:** Inheritance is an OOP }
@Override concept where one class (child or subclass) }----------------------------------------------------- public static void main(String[] args) {
void makeSound() { inherits the properties and behaviors (fields 12. **Write the use of `throws` statement MyRunnable myRunnable = new
System.out.println("Cat meows"); and methods) of another class (parent or in exception handling?** MyRunnable();
} superclass). It promotes code reuse and - **Definition:** The `throws` keyword in a Thread t1 = new
} establishes a hierarchical relationship method signature indicates that the method Thread(myRunnable);
between classes. might throw one or more exceptions, and it t1.start();
public class TestPolymorphism { informs the caller of the method to handle }
public static void main(String[] args) { **Example:** or declare these exceptions. }
Animal myAnimal = new Animal(); ```java —------------------------------------------
Animal myDog = new Dog(); class Animal { **Example:** 14. **What is thread priority?**
Animal myCat = new Cat(); void eat() { ```java - **Definition:** Thread priority in Java
System.out.println("This animal eats import java.io.*; determines the relative importance of a
myAnimal.makeSound(); // Outputs: food"); thread. Threads with higher priority are
Animal makes a sound } public class TestThrows { executed in preference to threads with
myDog.makeSound(); // Outputs: } // Method declaring an exception lower priority, though actual scheduling
Dog barks public static void readFile() throws depends on the thread scheduler of the
myCat.makeSound(); // Outputs: class Dog extends Animal { IOException { operating system.
Cat meows void bark() { FileReader file = new
} System.out.println("Dog barks"); FileReader("test.txt"); **Example:**
} } BufferedReader fileInput = new ```java
} BufferedReader(file); class MyThread extends Thread {
public void run() {
public class TestInheritance { throw new IOException("File not System.out.println("Running thread
public static void main(String[] args) { found"); name is: " +
Dog d = new Dog(); } Thread.currentThread().getName());
d System.out.println("Running thread
public static void main(String[] args) { priority is: " +
.eat(); // Inherited method try { Thread.currentThread().getPriority());
d.bark(); // Specific method readFile(); }
} } catch (IOException e) {
} System.out.println("Caught public static void main(String[] args) {
—----------------------------------------------- exception: " + e); MyThread t1 = new MyThread();
} MyThread t2 = new MyThread();
}
}
t1.setPriority(Thread.MIN_PRIORITY); // 1
t2.setPriority(Thread.MAX_PRIORITY); //
10
t1.start();
t2.start();
}
}
Sure, let's delve into each question with the 3. **What is the difference between `this` and 5. **Explain access protection in Java packages.** 7. **What are the advantages of
specific context as requested: `super` keyword in Java?** `StringBuffer` class over `String`
- **Access Modifiers:** Determine the visibility of classes, methods, and
- **`this` Keyword:**
variables. They are: class?**
- Refers to the current object instance.
1. **Explain the advantage of - Used to access members of the current class - **`private:`** Accessible only within the class. - **Mutability:**
Object-Oriented Programming Language.** including constructors, methods, and fields. - **`default` (no modifier):** Accessible only within the package. - `String`: Immutable. Once created, the
- **Advantages:** - Useful for distinguishing between instance - **`protected:`** Accessible within the package and by subclasses. value cannot be changed.
- **Modularity:** Code is organized into variables and parameters with the same name. - **`public:`** Accessible from any other class. - `StringBuffer`: Mutable. It can be
discrete objects that encapsulate data and modified without creating new objects.
**Example:**
behavior, making it easier to understand, **Example:** - **Performance:**
```java
modify, and troubleshoot. class TestThis { ```java - `StringBuffer` is more efficient for
- **Reusability:** Objects can be reused int x; package mypackage; operations that modify the string (like
across different programs or within the append, insert, delete) because it doesn't
same program, promoting DRY (Don't TestThis(int x) { public class MyClass { create new instances.
Repeat Yourself) principles. this.x = x; // 'this' refers to the current - **Thread Safety:**
private int privateVar = 1; // Private access
object's x
- **Extensibility:** New functionality can int defaultVar = 2; // Default access - `StringBuffer` is synchronized, making
}
be added by creating new objects or } protected int protectedVar = 3; // Protected access it thread-safe for use in multi-threaded
extending existing ones without modifying ``` public int publicVar = 4; // Public access environments.
the existing codebase.
- **Maintainability:** Encapsulation helps - **`super` Keyword:** public void display() { **Example:**
in hiding the internal implementation details, - Refers to the superclass (parent class) object. ```java
System.out.println("Private: " + privateVar);
- Used to access members (constructors,
making the system easier to maintain and System.out.println("Default: " + defaultVar); public class TestStringBuffer {
methods, and fields) of the superclass.
update. - Useful for invoking superclass constructors System.out.println("Protected: " + protectedVar); public static void main(String[] args) {
- **Scalability:** Easier to manage and and methods. System.out.println("Public: " + publicVar); // String example
expand complex systems by adding new } String str = "Hello";
objects and functionalities. **Example:** } str += " World";
```java System.out.println(str); // Outputs:
—---------------------------------------------
class Parent {
**Example:** 6. **Discuss the usability of `final` keyword in different contexts.** Hello World
void display() {
```java System.out.println("Parent class method"); - **Final Variable:**
class Animal { } - Once assigned, its value cannot be changed. // StringBuffer example
void eat() { } - **Final Method:** StringBuffer sb = new
System.out.println("This animal eats - Cannot be overridden by subclasses. StringBuffer("Hello");
food"); class Child extends Parent { sb.append(" World");
- **Final Class:**
void display() {
} - Cannot be extended (no subclass can be created). System.out.println(sb); // Outputs:
super.display(); // Calls the parent class
} method Hello World
System.out.println("Child class method"); **Examples:** }
class Dog extends Animal { } ```java }
void bark() { } // Final variable —-------------------------------------------
System.out.println("Dog barks"); final int CONSTANT = 100; 8. **`public static void main(String args[])` -
public class TestSuper {
} Write down the meaning of the words
public static void main(String[] args) {
} Child c = new Child(); // Final method mentioned above.**
c.display(); class Parent { - **public:** The method is accessible
public class TestOOP { } final void display() { from anywhere, allowing the JVM to call it
public static void main(String[] args) { } System.out.println("This is a final method."); from outside the class.
Dog d = new Dog(); ``` - **static:** The method belongs to the
}
—---------------------------------------------
d.eat(); // Inherited method } class rather than any instance, enabling the
4. **Write down the difference between class and
d.bark(); // Specific method interface?** JVM to call it without creating an instance of
} - **Class:** class Child extends Parent { the class.
} - A blueprint from which objects are created. // This will cause a compilation error - **void:** The method does not return
``` - Can contain fields, methods, constructors, // void display() { any value.
blocks, nested classes, and interfaces. - **main:** The name of the method that
// System.out.println("Cannot override");
- Supports inheritance.
2. **What is JVM and is it platform // } the JVM looks for as the entry point of the
- Can be instantiated (i.e., objects can be
independent?** created). } program.
- **Definition:** The Java Virtual Machine - Methods can have implementations. - **String args[]:** An array of `String`
(JVM) is an abstract computing machine // Final class arguments passed to the method. Used to
that enables a computer to run a Java **Example:** final class FinalClass { capture command-line arguments.
program. It provides a runtime environment ```java
void display() {
class Animal {
in which Java bytecode can be executed. System.out.println("This is a final class."); **Example:**
void eat() {
- **Platform Independence:** Yes, the System.out.println("This animal eats food"); } ```java
JVM is platform-independent at the } } public class MainExample {
bytecode level. Java programs are } public static void main(String[] args) {
compiled into bytecode which can be run on - **Interface:** // This will cause a compilation error System.out.println("Hello, World!");
any platform that has a compatible JVM. - A reference type in Java, similar to a class, but }
// class SubClass extends FinalClass {
is a collection of abstract methods and constants.
This enables Java to be a "write once, run // } }
- Cannot contain fields (except static final
anywhere" language. fields). —-------------------------------------------------------------------------- —------------------------------------------------
- Cannot be instantiated.
**Example:** - A class can implement multiple interfaces.
```java - Methods do not have implementations (default
public class HelloWorld { methods in interfaces can have implementations
since Java 8).
public static void main(String[] args) {
System.out.println("Hello, World!"); **Example:**
} ```java
} interface Animal {
// This program, once compiled to void eat();
bytecode, can run on any platform with a }
JVM.
class Dog implements Animal {
``` public void eat() {
System.out.println("Dog eats meat");
}
}
16. **Write basic difference between class 10. **Explain with example
13. **What are the advantages of using exception
and object.** handling in Java?** 9. **Discuss different types of
- **Class:** - **Advantages:** how does method overloading differ from method overriding?** constructors with examples.**
- Blueprint or template for creating - **Error Handling:** Provides a mechanism to - **Method Overloading:**
objects. handle runtime errors, improving program - Multiple methods in the same class with the same name but - **Default Constructor:**
- Defines properties and behaviors robustness. - A constructor with no parameters. If no
different parameters (type or number).
- **Separation of Error-Handling Code:** Allows
(fields and methods) that the objects constructor is defined, Java provides a
separation of normal code from error-handling
created from the class will have. code, making the code cleaner and easier to **Example:** default constructor.
understand. ```java - **Parameterized Constructor:**
**Example:** - **Propagating Errors Up the Call Stack:** class OverloadingExample { - A constructor that takes arguments to
```java Allows exceptions to be propagated up the call void display(int a) { initialize the object with specific values.
class Car { stack, so higher-level methods can handle them. - **Copy Constructor:**
System.out.println("Argument: " + a);
- **Grouping and Differentiating Error Types:**
String model; } - A constructor that creates a new object
Enables different types of errors to be grouped and
int year; differentiated using different exception classes. as a copy of an existing object.
void display(String b) {
void displayInfo() { **Example:** System.out.println("Argument: " + b); **Examples:**
System.out.println("Model: " + ```java } ```java
model + ", Year: " + year); public class ExceptionHandlingAdvantages { class MyClass {
public static void main(String[] args) {
} public static void main(String[] args) { int x;
try {
} int[] arr = new int[5]; OverloadingExample obj = new OverloadingExample();
``` arr[10] = 50; // This will throw obj.display(10); // Outputs: Argument: 10 // Default constructor
ArrayIndexOutOfBoundsException obj.display("Hello"); // Outputs: Argument: Hello MyClass() {
- **Object:** } catch (ArrayIndexOutOfBoundsException } x = 0;
- Instance of a class. e) { }
}
System.out.println("Array index out of
- Contains actual values and can ```
bounds: " + e.getMessage());
perform actions defined by the class. } finally { // Parameterized constructor
System.out.println("Error handling - **Method Overriding:** MyClass(int val) {
**Example:** complete."); - A subclass provides a specific implementation for a method that is x = val;
```java } already defined in its superclass. }
public class TestClassObject { }
}
public static void main(String[] args) { **Example:** // Copy constructor
Car myCar = new Car(); —---------------------------------------------- ```java MyClass(MyClass other) {
myCar.model = "Toyota"; 12. **What are checked and unchecked class Parent { x = other.x;
myCar.year = 2020; exceptions?** void display() { }
myCar.displayInfo(); // Outputs: - **Checked Exceptions:** System.out.println("Parent class method");
Model: Toyota, Year: 2020 - Exceptions that are checked at compile-time. public static void main(String[] args) {
}
The compiler ensures that they are handled using
} } MyClass obj1 = new MyClass();
try-catch blocks or declared in the method
} signature using the `throws` keyword. MyClass obj2 = new MyClass(10);
``` - Examples: `IOException`, `SQLException`. class Child extends Parent { MyClass obj3 = new MyClass(obj2);
@Override
``` **Example:** void display() { System.out.println(obj1.x); //
```java Outputs: 0
System.out.println("Child class method");
import java.io.*;
18. **Write the uses of `final` keyword.** } System.out.println(obj2.x); //
- **Final Variable:** public class CheckedExceptionExample { } Outputs: 10
- Value cannot be changed once public static void main(String[] args) { System.out.println(obj3.x); //
assigned. try { public class OverridingExample { Outputs: 10
FileReader file = new public static void main(String[] args) { }
**Example:** FileReader("test.txt"); }
Parent obj = new Child();
} catch (FileNotFoundException e) {
```java obj.display(); // Outputs: Child class method
System.out.println("File not found: " +
final int MAX_VALUE = 100; e.getMessage()); } —--------------------------------
``` } } 15. **Explain types of package in Java.**
} —------------------------------------- - **Types of Packages:**
- **Final Method:** } 11. **Explain how exception handling is achieved in Java.** - **Built-in Packages:** Provided by the
- Cannot be overridden by subclasses. ``` Java API. Examples include `java.lang`,
- **Exception Handling Mechanism:**
- **try:** Encloses code that might throw an exception. `java.util`, `java.io`.
- **Unchecked Exceptions:**
**Example:** - Exceptions that are not checked at - **catch:** Catches and handles the exception thrown by the try - **User-defined Packages:** Created
```java compile-time but occur at runtime. These are block. by users to organize their own classes and
class Parent { subclasses of `RuntimeException`. - **finally:** Contains code that is always executed after the try block, interfaces.
final void display() { - Examples: `NullPointerException`, regardless of whether an exception was thrown.
System.out.println("Final method"); `ArithmeticException`. **Example:**
- **throw:** Used to explicitly throw an exception.
} - **throws:** Indicates the exceptions that a method can throw to the ```java
**Example:**
} ```java caller. // User-defined package
``` public class UncheckedExceptionExample { package mypackage;
public static void main(String[] args) { **Example:**
- **Final Class:** String str = null; ```java public class MyClass {
- Cannot be extended. System.out.println(str.length()); // This will public void display() {
public class ExceptionHandlingExample {
throw NullPointerException
public static void main(String[] args) { System.out.println("Hello from
}
**Example:** } try { mypackage");
```java int data = 100 / 0; // This will throw an ArithmeticException }
final class FinalClass { —------------------------------------------ } catch (ArithmeticException e) { }
// class definition System.out.println("ArithmeticException caught: " +
} e.getMessage()); // Using the user-defined package
—------------------------------------ } finally { import mypackage.MyClass;
System.out.println("This block is always executed.");
} public class TestPackage {
} public static void main(String[] args) {
} MyClass obj = new MyClass();
obj.display();
}
14. **What is file handling in Java?**
22. **What do you mean by thread 17. **Write down the difference between POP and OOP programming }
- **Definition:** File handling in Java involves
synchronization?** reading from and writing to files. Java provides the languages.**
- **Definition:** Thread synchronization is `java.io` package to perform input and output - **Procedure-Oriented Programming (POP):** 20. **Describe different forms of
a mechanism that ensures that two or more operations on files. - Focuses on functions or procedures. inheritance with block diagrams.**
concurrent threads do not simultaneously - **Classes Used:** - Data and functions are separate. - **Single Inheritance:**
execute some particular program segment - `FileReader`, `BufferedReader` for reading - One class inherits from one
- Less modular, harder to manage for larger projects.
files.
known as a critical section. superclass.
- `FileWriter`, `BufferedWriter` for writing to
- **Purpose:** Prevents thread files. **Example:**
interference and consistency problems. ```c **Diagram:**
- **Methods:** **Example:** // C language example ```
- **Synchronized Method:** Locks the ```java #include <stdio.h>
method for a single thread. import java.io.*;
- **Synchronized Block:** Locks a block void display() {
A
public class FileHandlingExample { |
of code within a method for a single thread. public static void main(String[] args) { printf("Hello, World!");
// Writing to a file }
B
**Example:** try (BufferedWriter writer = new
```java BufferedWriter(new FileWriter("output.txt"))) { int main() {
class Counter { writer.write("Hello, World!");
display();
} catch (IOException e) {
private int count = 0; return 0;
System.out.println("Error writing to file: "
+ e.getMessage()); }
**Example:**
public synchronized void increment() { } ```
```java
count++;
// Reading from a file
class A { }
} - **Object-Oriented Programming (OOP):**
try (BufferedReader reader = new class B extends A { }
- Focuses on objects that encapsulate data and behavior.
BufferedReader(new FileReader("output.txt"))) { ```
public int getCount() { - Promotes reuse, modularity, and maintainability.
String line;
return count; while ((line = reader.readLine()) != null) { - Easier to manage and scale for larger projects.
- **Multiple Inheritance (Not supported
} System.out.println(line); directly in Java):**
} } **Example:**
} catch (IOException e) {
- One class inherits from multiple
```java
System.out.println("Error reading from superclasses. (Achieved through interfaces)
public class ThreadSynchronization { class Car {
file: " + e.getMessage());
public static void main(String[] args) { String model;
} **Diagram:**
Counter counter = new Counter(); } int year;
```
}
Thread t1 = new Thread(() -> { —------------------------------------------------ void displayInfo() {
for (int i = 0; i < 1000; i++) { 19. **Write down the difference between interface System.out.println("Model: " + model + ", Year: " + year); A B
counter.increment(); and abstract class.**
- **Interface:**
} \ /
} } \/
- Cannot have instance variables, only static
}); final constants. C
- All methods are abstract (default methods can public class TestOOP {
Thread t2 = new Thread(() -> { have implementations since Java 8). public static void main(String[] args) {
for (int i = 0; i < 1000; i++) { - A class can implement multiple interfaces. Car myCar = new Car(); **Example:**
counter.increment(); myCar.model = "Toyota"; ```java
**Example:**
} myCar.year = 2020; interface A { }
```java
}); myCar.displayInfo(); interface B { }
} class C implements A, B { }
t1.start(); interface Animal { } ```
t2.start(); void eat(); —---------------------------------------------------------
} - **Multilevel Inheritance:**
21. **Explain the complete lifecycle of a thread with diagram.**
try { - **Lifecycle Stages:** - A class is derived from another
class Dog implements Animal {
t1.join(); public void eat() { - **New:** Thread is created. derived class.
t2.join(); System.out.println("Dog eats meat"); - **Runnable:** Thread is ready to run.
} catch (InterruptedException e) { } - **Running:** Thread is executing. **Diagram:**
e.printStackTrace(); } - **Blocked:** Thread is blocked waiting for a resource.
} ```
- **Terminated:** Thread has finished execution.
A
- **Abstract Class:** |
System.out.println("Final count: " + - Can have instance variables. **Diagram:**
counter.getCount()); B
- Can have both abstract and concrete ```
—--------------------------------------- methods. New -> Runnable -> Running -> Terminated
|
- A class can extend only one abstract class. \-> Blocked ->/
C
```
**Example:**
```java
abstract class Animal { **Example:**
abstract void eat(); ```java
**Example:**
void sleep() { class MyThread extends Thread {
System.out.println("Animal sleeps");
```java
public void run() {
} class A { }
System.out.println("Thread is running");
} class B extends A { }
}
class C extends B { }
class Dog extends Animal { }
void eat() {
System.out.println("Dog eats meat"); public class ThreadLifecycle {
} public static void main(String[] args) {
}
MyThread t = new MyThread(); // New state
—----------------------------------------------
t.start(); // Runnable state
}
}
—---------------------------
### 2. Explain dynamic method dispatch in method
### 1. Discuss different types of ### 4. Write a code to create a package and then use it in a program.
overriding with a proper example.
constructors with examples.
Dynamic method dispatch, also known as runtime **Creating a package:** - **Hierarchical Inheritance:**
In Java, constructors are special methods polymorphism, is a process in which a call to an 1. Create a directory structure for the package. - Multiple classes inherit from one
used to initialize objects. There are primarily overridden method is resolved at runtime rather 2. Define classes in the package. superclass.
two types of constructors: than compile time. This is achieved through
method overriding in Java.
**Example:** **Diagram:**
1. **Default Constructor:** **Example:** ```java ```
- A constructor with no parameters. ```java // Save as MyPackageClass.java in com/example directory A
- Provided by Java if no other class Parent { package com.example; /\
constructors are defined. void show() { B C
System.out.println("Parent's show()"); ```
public class MyPackageClass {
}
**Example:** public void display() {
}
```java System.out.println("Hello from MyPackageClass"); **Example:**
class DefaultConstructor { class Child extends Parent { } ```java
int x; @Override } class A { }
void show() { ``` class B extends A { }
// Default constructor System.out.println("Child's show()"); class C extends A { }
}
DefaultConstructor() { **Using the package in another program:** ```
}
x = 10;
} public class DynamicMethodDispatch { **Example:** - **Hybrid Inheritance:**
public static void main(String[] args) { ```java - Combination of two or more types of
public static void main(String[] args) { Parent obj; // Save as TestPackage.java in the default directory inheritance. (Achieved through interfaces)
DefaultConstructor obj = new import com.example.MyPackageClass;
// Object of Parent class
DefaultConstructor(); **Diagram:**
obj = new Parent();
System.out.println("x = " + obj.x); // obj.show(); // Outputs: Parent's show() public class TestPackage { ```
Outputs: x = 10 public static void main(String[] args) { A
} // Object of Child class MyPackageClass obj = new MyPackageClass(); /\
} obj = new Child(); obj.display(); // Outputs: Hello from MyPackageClass B C
``` obj.show(); // Outputs: Child's show() \/
}
}
} D
}
2. **Parameterized Constructor:** ``` ``` ```
- A constructor that takes one or more In this example, `Parent` and `Child` classes both
parameters. have a method `show()`. The method call **Steps to compile and run:** **Example:**
- Used to initialize an object with specific `obj.show()` is resolved at runtime depending on 1. Compile the class in the package: ```java
values. the object type (Parent or Child) that `obj` is interface A { }
```sh
referring to.
javac com/example/MyPackageClass.java interface B extends A { }
**Example:** —---------------------------------------------------- ``` interface C extends A { }
```java ### 3. With a suitable code explain how we can class D implements B, C { }
class ParameterizedConstructor { achieve multiple inheritance in Java. 2. Compile the class using the package:
int x; —------------------------------------
```sh
Java does not support multiple inheritance with
javac -cp . TestPackage.java
// Parameterized constructor classes to avoid complexity and simplify the
ParameterizedConstructor(int a) { design. However, multiple inheritance can be ```
x = a; achieved using interfaces.
} **Example:** 3. Run the program:
interface A { ```sh
public static void main(String[] args) { void displayA(); java -cp . TestPackage
ParameterizedConstructor obj = new }
```
ParameterizedConstructor(20);
System.out.println("x = " + obj.x); // interface B { This will output: `Hello from MyPackageClass`.
Outputs: x = 20 void displayB();
} } —--------------------------------------------------------------
}
``` class C implements A, B {
@Override
3. **Copy Constructor:** public void displayA() {
System.out.println("Display from A");
- A constructor that creates a new object
}
as a copy of an existing object.
**Example: @Override
class CopyConstructor { public void displayB() {
int x; System.out.println("Display from B");
}
// Parameterized constructor
CopyConstructor(int a) { public static void main(String[] args) {
x = a; C obj = new C();
} obj.displayA(); // Outputs: Display from A
obj.displayB(); // Outputs: Display from B }}
// Copy constructor ```
CopyConstructor(CopyConstructor obj) { In this example, class `C` implements two
x = obj.x; interfaces `A` and `B`, thereby achieving multiple
} inheritance.
String line;
while ((line = reader.readLine()) != null) {
// Convert line to upper case and write to upper.txt
writer.write(line.toUpperCase());
writer.newLine();
}
reader.close();
writer.close();
**Explanation:**
1. **Reading from "lower.txt":**
- Use `BufferedReader` to read the file line by line.
2. **Writing to "upper.txt":**
- Convert each line to uppercase using `String.toUpperCase()` and
write it to "upper.txt" using `BufferedWriter`.
**File Structure:**
- `lower.txt`: This file should contain the text that you want to convert to
uppercase.
- `upper.txt`: This file will be created or overwritten with the uppercase
content from `lower.txt`.