1. Method Overriding and Dynamic Method Dispatch
I. Introduction to Method Overriding
Method Overriding occurs when a subclass (child class) has the same method as declared in the parent class. It is used to provide the specific implementation of a method that is already provided by its superclass.
- Rules: The method must have the same name, same return type, and same parameter list.
- Purpose: To achieve Runtime Polymorphism.
II. Dynamic Method Dispatch (Runtime Polymorphism)
Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at runtime rather than compile-time.
- The Concept: A superclass reference variable can refer to a subclass object. Java determines which version of an overridden method to call based on the type of the object being referred to, not the type of the reference variable.
III. Example Program
class Bank {
float getRateOfInterest() { return 0; }
}
class SBI extends Bank {
float getRateOfInterest() { return 8.4f; }
}
class ICICI extends Bank {
float getRateOfInterest() { return 7.3f; }
}
public class TestPolymorphism {
public static void main(String args[]) {
Bank b; // Superclass reference
b = new SBI(); // Reference points to SBI object
System.out.println("SBI Rate: " + b.getRateOfInterest());
b = new ICICI(); // Reference points to ICICI object
System.out.println("ICICI Rate: " + b.getRateOfInterest());
}
}
2. The super Keyword in Detail
I. Definition
The super keyword in Java is a reference variable used to refer to immediate parent class objects.
II. Three Major Uses of super
- To refer parent class instance variable: Used when a subclass and parent class have variables with the same name.
- To invoke parent class method: Used when we want to call a parent method that has been overridden in the child class.
- To invoke parent class constructor: super() is used to call the parent constructor. It must be the first statement in the subclass constructor.
III. Comprehensive Example
class Animal {
String color = "White";
Animal() { System.out.println("Animal is created"); }
void eat() { System.out.println("Eating..."); }
}
class Dog extends Animal {
String color = "Black";
Dog() {
super(); // Calls parent constructor
System.out.println("Dog is created");
}
void printColor() {
System.out.println(color); // Prints Black
System.out.println(super.color); // Prints White (parent variable)
}
void eat() {
System.out.println("Eating bread...");
super.eat(); // Calls parent method
}
}
3. Abstract Classes vs. Interfaces
I. Abstract Class
A class declared with the abstract keyword. It can have abstract methods (without body) and concrete methods (with body). It cannot be instantiated.
II. Interface
An interface is a blueprint of a class. It contains only abstract methods and static constants. It is used to achieve 100% abstraction and multiple inheritance.
III. Comparison Table
| Feature | Abstract Class | Interface |
|---|---|---|
| Methods | Can have abstract and non-abstract methods. | Traditionally only abstract methods (until Java 8). |
| Variables | Can have final, non-final, static, and non-static variables. | Only static and final variables. |
| Inheritance | A class can extend only one abstract class. | A class can implement multiple interfaces. |
IV. Example
interface Printable { void print(); } // Interface
abstract class Shape { // Abstract Class
abstract void draw();
void msg() { System.out.println("Method from Abstract Class"); }
}
4. Packages in Java: Types and Access
I. Definition
A Java package is a group of similar types of classes, interfaces, and sub-packages. It acts as a directory to organize code and prevent naming conflicts.
II. Types of Packages
- Built-in Packages: Provided by Java API (e.g., java.lang, java.util, java.io).
- User-defined Packages: Created by the programmer (e.g., package com.myapp.test).
III. Ways to Access a Package
- Importing everything: import packagename.*;
- Importing specific class: import packagename.ClassName;
- Fully qualified name: packagename.ClassName obj = new packagename.ClassName(); (No import needed).
IV. Example
// Saving as First.java
package learnjava;
public class First {
public void msg() { System.out.println("Hello from Package"); }
}
// Accessing from another class
import learnjava.First;
class Second {
public static void main(String args[]) {
First obj = new First();
obj.msg();
}
}
5. Exception Handling Mechanism
I. Core Keywords
- try: Used to enclose the code that might throw an exception.
- catch: Used to handle the exception. It must follow a try block.
- finally: Used to execute important code (like closing resources). It executes regardless of whether an exception is handled.
- throw: Used to explicitly throw an exception.
- throws: Used in method signatures to declare exceptions that might occur.
II. Example Program
class TestException {
static void validate(int age) throws ArithmeticException {
if(age < 18) throw new ArithmeticException("Not valid age");
else System.out.println("Welcome to vote");
}
public static void main(String args[]) {
try {
validate(13);
} catch(ArithmeticException e) {
System.out.println("Exception handled: " + e.getMessage());
} finally {
System.out.println("Finally block always executes");
}
}
}
6. Built-in and User-Defined Exceptions
I. Built-in Exceptions
Java provides a rich set of built-in exceptions under the java.lang.Throwable class.
- ArithmeticException: Division by zero.
- NullPointerException: Accessing a null object.
- ArrayIndexOutOfBoundsException: Accessing wrong array index.
II. User-Defined (Custom) Exceptions
To create a custom exception, you must extend the Exception class. This is used for business logic errors (e.g., InsufficientFundsException).
III. Example of Custom Exception
class MyException extends Exception {
MyException(String s) { super(s); }
}
class Main {
public static void main(String args[]) {
try {
throw new MyException("This is my custom error");
} catch (MyException ex) {
System.out.println(ex.getMessage());
}
}
}
7. The final Keyword in Inheritance
I. Introduction
The final keyword is used to restrict the user. It can be used in three ways:
- Final Variable: To create a constant. Its value cannot be changed.
- Final Method: To prevent method overriding. If a parent method is final, the child cannot redefine it.
- Final Class: To prevent inheritance. A final class cannot be extended.
II. Example Program
final class SuperClass { // Cannot be inherited
final int limit = 100; // Constant value
final void display() { // Cannot be overridden
System.out.println("Final Method");
}
}
// class SubClass extends SuperClass { } // Compile-time error
III. Role in Security
By declaring classes like String as final, Java ensures that the fundamental behavior of the class cannot be altered by any user-defined subclass, making the language more secure and stable.
0 Comments