Inheritance UNIT 2 CHATGPT
Inheritance UNIT 2 CHATGPT
Inheritance is a mechanism where one class acquires the properties and behaviors of another
class, promoting code reuse and hierarchy.
Basic Concepts:
Parent Class (Super Class): The class whose properties and methods are inherited.
Child Class (Sub Class): The class that inherits properties and methods.
Types of Inheritance:
Polymorphism
Polymorphism allows methods to perform different tasks based on the object that calls them.
Method Overloading:
Defining multiple methods with the same name but different parameter lists in the same
class.
Example:
java
Copy code
void display(int a);
void display(String b);
Method Overriding:
Redefining a method in the subclass that already exists in the parent class.
Example:
java
Copy code
@Override
void display() { ... }
Abstract Classes:
Classes that cannot be instantiated and may contain abstract methods (without
implementation).
Example:
java
Copy code
abstract class Shape {
abstract void draw();
}
java
Copy code
Shape s = new Circle();
s.draw(); // Executes Circle's draw method
final Keyword:
Packages
Access Protection:
Classes in the same package can access each other's members (except private
members).
Importing Packages:
import packageName.ClassName;
import packageName.*; (imports all classes in a package)
Interfaces
Definition:
Implementation:
Extending Interfaces:
Exception Handling
Keywords:
ArithmeticException
NullPointerException
ArrayIndexOutOfBoundsException
java
Copy code
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}