Object Oriented Programming
Object Oriented Programming
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
package mypackage;
MainProgram.java
import mypackage.ArithmeticOperations;
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
t1.start();
t2.start();
}
}
c) Three Events in Java
. ActionEvent: Generated by components like buttons.
.
Example:
button.addActionListener(e -> System.out.println("Button clicked!"));
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.
class Overload {
void add(int a, int b) { System.out.println(a + b); }
void add(double a, double b) { System.out.println(a + b); }
}
class Person {
private String name; // Data hidden
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
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 {}