Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Object Oriented Programming

The document outlines key differences between various Java concepts such as 'throw' vs 'throws', 'final' vs 'finally', abstract classes vs interfaces, and exception handling. It also covers Java's threading model, including thread life cycle, multithreading, and communication between threads. Additionally, it discusses object-oriented programming principles like encapsulation, inheritance, and polymorphism, along with examples and code snippets.

Uploaded by

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

Object Oriented Programming

The document outlines key differences between various Java concepts such as 'throw' vs 'throws', 'final' vs 'finally', abstract classes vs interfaces, and exception handling. It also covers Java's threading model, including thread life cycle, multithreading, and communication between threads. Additionally, it discusses object-oriented programming principles like encapsulation, inheritance, and polymorphism, along with examples and code snippets.

Uploaded by

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

1) Differences between 'throw' and 'throws' clause

Aspect throw throws


Purpose Used to explicitly throw Declares exceptions that
an exception. a method can throw.
Location Used inside a method or Used in a method
block of code. declaration.
Type Used to throw a single Specifies multiple
exception instance. exception types.
Example throw new void readFile() throws
IOException("File not IOException {}
found");
2) Differences between final and finally
Aspect final finally
Purpose A modifier for variables, Used to execute a block
methods, and classes to of code after a try-catch
make them immutable. block.
Usage Ensures no modification Used for cleanup
or overriding. activities.
Scope Variable, method, or Block of code in
class declaration. exception handling.
Example final int MAX = 100; finally
{ System.out.println("Cle
anup"); }
3) Differences between Abstract Classes and Interfaces
Aspect Abstract Class Interface
Definition A class that may contain A blueprint that contains
abstract and concrete only abstract methods
methods. (or default/static
methods in newer
versions).
Inheritance Supports single Allows multiple
inheritance. inheritance.
Keyword Declared with the Declared with the
abstract keyword. interface keyword.
Implementation Can have constructors Cannot have
and instance variables. constructors or instance
variables.
Access Modifiers Methods can have any Methods are public by
access modifier. default.
8) Short Notes
i) Link and Association:
● Association: Represents a relationship between two or more objects (e.g., "a teacher
teaches students").
● Link: A specific instance of an association that connects two objects. For example, a
specific teacher teaching a specific student is a link in the association.
ii) Thread Life-Cycle:
A thread goes through five states:
. New: Created but not started.
. Runnable: Ready to run but waiting for CPU time.
. Running: Actively executing.
. Blocked/Waiting: Waiting for a resource or signal.
. Terminated: Execution is completed.
iii) Abstraction:
The process of hiding implementation details and showing only the essential features to the user.
In Java, abstraction can be achieved using abstract classes and interfaces.

9) Short Notes
i) Dynamic Method Dispatch:
Also known as runtime polymorphism, it refers to the process where a call to an overridden
method is resolved at runtime rather than compile-time.

class Animal {
void sound() { System.out.println("Animal sound"); }
}
class Dog extends Animal {
void sound() { System.out.println("Dog barks"); }
}
Animal a = new Dog();
a.sound(); // Outputs: Dog barks

ii) Dynamic Binding:


Binding refers to linking a method call to its definition. Dynamic binding happens at runtime and
applies to overridden methods.
iii) Encapsulation:
Encapsulation is the bundling of data (fields) and methods that operate on the data into a single
unit (class) while restricting access using access modifiers like private.

10) Java Package Example


ArithmeticOperations.java

package mypackage;

public class ArithmeticOperations {


public int add(int a, int b) {
return a + b;
}

public int subtract(int a, int b) {


return a - b;
}

public int multiply(int a, int b) {


return a * b;
}

public int divide(int a, int b) {


if (b != 0) return a / b;
else throw new ArithmeticException("Division by zero");
}
}

MainProgram.java

import mypackage.ArithmeticOperations;

public class MainProgram {


public static void main(String[] args) {
ArithmeticOperations ao = new ArithmeticOperations();

System.out.println("Addition: " + ao.add(10, 5));


System.out.println("Subtraction: " + ao.subtract(10, 5));
System.out.println("Multiplication: " + ao.multiply(10, 5));
System.out.println("Division: " + ao.divide(10, 5));
}
}

11) Exception Handling


a) Exceptions:
Exceptions are unwanted or unexpected events that disrupt the normal flow of a program.
● System-defined exceptions: Predefined in Java (e.g., NullPointerException,
ArrayIndexOutOfBoundsException).
● User-defined exceptions: Custom exceptions created by extending the Exception class.

class MyException extends Exception {


MyException(String message) {
super(message);
}
}

public class TestException {


public static void main(String[] args) {
try {
throw new MyException("Custom Exception");
} catch (MyException e) {
System.out.println(e.getMessage());
}
}
}

b) Use of this and super:


● this: Refers to the current object of a class.
● super: Refers to the parent class object.
c) Difference between == and equals:
Aspect == equals()
Purpose Checks reference Checks value equality.
equality.
Applicable to Primitive types and Only objects.
objects.
Example str1 == str2 str1.equals(str2)

7) Exceptions
a) What are exceptions?
Exceptions are errors that occur during the execution of a program, disrupting its normal flow.
Java provides mechanisms to handle these exceptions to maintain program stability.
● System-defined exceptions: Predefined in Java and part of the java.lang package.
Examples:
○ ArithmeticException (e.g., division by zero)
○ ArrayIndexOutOfBoundsException (e.g., accessing an invalid index)
int a = 10 / 0; // ArithmeticException

User-defined exceptions: Custom exceptions created by extending the Exception class.


Example:

class MyException extends Exception {


public MyException(String message) {
super(message);
}
}
public class Test {
public static void main(String[] args) {
try {
throw new MyException("Custom Exception Occurred");
} catch (MyException e) {
System.out.println(e.getMessage());
}
}
}

b) Try and Catch Block


●Definition:
○ A try block contains code that may throw exceptions.
○ A catch block handles those exceptions.
Example:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
Is it essential to catch all exceptions?
No, but unhandled exceptions can crash the program. Checked exceptions must be caught or
declared using throws, while unchecked exceptions (e.g., NullPointerException) may not be
caught explicitly.

8) Applets, Threads, and Events


a) Difference between Applet, Frame, and Panel
Aspect Applet Frame Panel
Definition A small Java A top-level A container to
program run in a window in a GUI. hold components.
browser or applet
viewer.
Execution Requires a Standalone Used inside a
browser or viewer. application. Frame or Applet.
Lifecycle Has init(), start(), No special No special
and stop() lifecycle methods. lifecycle methods.
methods.
b) Thread Communication
Threads communicate using methods like wait(), notify(), and notifyAll().
Example:
class Shared {
synchronized void printMessage(String msg) {
try {
System.out.println(msg);
wait(); // Pauses thread
} catch (InterruptedException e) {
System.out.println(e);
}
}
synchronized void resumeThread() {
notify(); // Resumes thread
}
}
public class ThreadComm {
public static void main(String[] args) {
Shared shared = new Shared();
Thread t1 = new Thread(() -> shared.printMessage("Thread 1 waiting..."));
Thread t2 = new Thread(shared::resumeThread);

t1.start();
t2.start();
}
}
c) Three Events in Java
. ActionEvent: Generated by components like buttons.
.
Example:
button.addActionListener(e -> System.out.println("Button clicked!"));

MouseEvent: Generated by mouse actions.


Example:
frame.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked");
}
});

KeyEvent: Generated by keyboard inputs.


Example:

frame.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
System.out.println("Key pressed: " + e.getKeyChar());
}
});

Short Notes
a) Interface:
An interface in Java is a blueprint containing abstract methods and static constants. It allows
multiple inheritance and polymorphism.
Example:

interface Animal {
void sound();
}
class Dog implements Animal {
public void sound() {
System.out.println("Dog barks");
}
}

b) Abstraction:
Hiding implementation details while showing functionality. Achieved using abstract classes or
interfaces.
c) Inheritance:
Allows a class to inherit properties and methods from another class using the extends keyword.
Example:
class Parent {
void display() {
System.out.println("Parent");
}
}
class Child extends Parent {}

d) Encapsulation:
Binding data and methods together and restricting access using access modifiers.
e) Virtual Method Table (VMT):
A data structure used to support dynamic method dispatch. It maps method calls to the actual
method implementations.

10) Overloading, Class, Constructor


a) Method Overloading
Defining multiple methods with the same name but different parameter lists.
Example:

class Overload {
void add(int a, int b) { System.out.println(a + b); }
void add(double a, double b) { System.out.println(a + b); }
}

b) Class and Data Hiding


A class is a blueprint for creating objects. Data hiding is achieved using private fields and public
methods.
Example:

class Person {
private String name; // Data hidden
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}

c) Constructor and Finalize


● A constructor initializes an object when it is created.
● finalize() cleans up resources before an object is garbage collected.

11) Thread and Applet Lifecycle, Wrapper Classes


a) Thread Life Cycle
. New: Thread is created.
. Runnable: Ready to run.
. Running: Executing.
. Waiting/Blocked: Waiting for resources.
. Terminated: Completed execution.
b) Applet Life Cycle
. init(): Initializes the applet.
. start(): Begins execution.
. stop(): Stops execution temporarily.
. destroy(): Cleans up resources.
c) Wrapper Classes and Bytecode
● Wrapper Classes: Provide object representations of primitive types (e.g., Integer, Double).
● Need: Used for collection frameworks, type conversion, etc.
● Bytecode: Intermediate code generated by the Java compiler, executed by the JVM.

7) Procedural-Oriented Programming vs. Object-Oriented Programming


Aspect Procedural-Oriented Object-Oriented
Programming (POP) Programming (OOP)
Definition Focuses on functions Focuses on objects that
(procedures) to operate encapsulate data and
on data. methods.
Approach Top-down approach. Bottom-up approach.
Data Security Data is not hidden; Data is encapsulated
functions operate and secured within
directly. objects.
Reusability Limited reuse through Promotes reuse via
functions. inheritance and
polymorphism.
Example C, Pascal Java, C++
b) Why is Java called a ‘strongly typed’ language?
Java is strongly typed because:
. Each variable has a specific type that must be declared before use.
. Type mismatches are flagged as errors at compile time.
. Automatic type conversion follows strict rules (e.g., no implicit conversion between int and
boolean).

c) Upcasting vs. Downcasting


Aspect Upcasting Downcasting
Definition Converting a subclass Converting a superclass
object to a superclass
type.
Converting a superclass
object to a superclass object to a subclass
type. type.
Safety Safe and implicit. Risky and requires
explicit casting.
Example Animal a = new Dog(); Dog d = (Dog) a;
Example:
class Animal {
void sound() { System.out.println("Animal sound"); }
}
class Dog extends Animal {
void sound() { System.out.println("Dog barks"); }
}
public class Test {
public static void main(String[] args) {
Animal a = new Dog(); // Upcasting
Dog d = (Dog) a; // Downcasting
}
}
d) What does the super keyword do?
The super keyword is used in Java to:
. Access the parent class constructor.
. Call parent class methods.
. Access parent class fields.
Example:
class Parent {
void display() { System.out.println("Parent method"); }
}
class Child extends Parent {
void display() {
super.display(); // Calls Parent's display
System.out.println("Child method");
}
}
8) Multithreading in Java
a) What is Multithreading?
Multithreading allows a program to execute multiple threads simultaneously. It improves
performance and allows efficient utilization of CPU.

b) Program to Run Main Thread and Child Thread Simultaneously


class ChildThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Child Thread: " + i);
}
}
}
public class MainThreadExample {
public static void main(String[] args) {
ChildThread ct = new ChildThread();
ct.start(); // Start child thread

for (int i = 1; i <= 5; i++) {


System.out.println("Main Thread: " + i);
}
}
}

c) Can a method with no exceptions be overridden to throw exceptions?


No. If the parent class method does not declare any exceptions, the overriding method in the
subclass cannot declare checked exceptions.
9) Java Thread, Monitor, and Other Concepts
a) What are Java "Thread" and "Monitor"?
● Thread: A lightweight subprocess for concurrent execution.
● Monitor: A synchronization construct in Java that ensures only one thread accesses a
critical section of code at a time. It's implemented using the synchronized keyword.

b) Dynamic Binding vs. Message Passing


Aspect Dynamic Binding Message Passing
Definition Runtime method call Communication between
resolution for overridden objects via methods.
methods.
Purpose Supports polymorphism. Promotes encapsulation
and modularity.
c) Template and Package
Template: A general blueprint or pattern, not commonly used in Java (specific to C++).

● Package: A namespace to organize classes and interfaces. Example:
package mypackage;
public class MyClass {
public void display() { System.out.println("Hello!"); }
}
b) Why Java Does Not Support Multiple Inheritance?
Java avoids multiple inheritance to prevent ambiguity caused by the "Diamond Problem." Instead,
it uses interfaces.
c) Interface vs. Abstract Class
Aspect Interface Abstract Class
Methods Only abstract methods Can have both abstract
(until Java 8). and concrete methods.
Inheritance Allows multiple Single inheritance only.
inheritance.
Example of Interface:
interface Drawable {
void draw();
}
class Circle implements Drawable {
public void draw() {
System.out.println("Drawing Circle");
}
}
d) Data Abstraction vs. Encapsulation
Aspect Data Abstraction Encapsulation
Definition Hides implementation Restricts access to data.
details.
Focus Focuses on what an Focuses on how data is
object does. secured.
11) Miscellaneous
a) Thread Life Cycle
. New: Thread is created but not started.
. Runnable: Ready to execute.
. Running: Actively executing.
. Blocked/Waiting: Paused waiting for resources.
. Terminated: Execution is completed.
b) Applet Life Cycle
. init(): Initializes the applet.
. start(): Begins or resumes execution.
. stop(): Pauses execution.
. destroy(): Cleans up resources.
c) Wrapper Classes and Byte Code
● Wrapper Classes: Provide object equivalents for primitive types (e.g., Integer, Double).
● Bytecode: Intermediate machine-independent code executed by the JVM.
10) Forms of Inheritance in Java
a) Forms of Inheritance
. Single Inheritance:java
Copy code

class Parent {}
. class Child extends Parent {}
.

. Multilevel Inheritance:java
Copy code

class A {}
. class B extends A {}
. class C extends B {}
.

. Hierarchical Inheritance:java
Copy code

class Parent {}
. class Child1 extends Parent {}
. class Child2 extends Parent {}

You might also like