Unit-III Inheritance and Polymorphism
1. Inheritance in Java
Inheritance is a core concept of Object-Oriented Programming where
one class acquires properties and behaviors of another class using the
`extends` keyword. It promotes code reuse and reduces redundancy. Java
supports single, multilevel, and hierarchical inheritance. It does not
support multiple inheritance using classes to avoid ambiguity, but it can
be achieved through interfaces. The class being inherited is called the
superclass, and the class that inherits is called the subclass. It helps in
building a parent-child relationship between classes.
**Example:**
```java
class Animal {
void eat() { [Link]("Eating"); }
}
class Dog extends Animal {
void bark() { [Link]("Barking"); }
}
```
2. Super and Sub Class
A superclass is a parent class whose features are inherited, whereas a
subclass is a child class that inherits those features. The `super` keyword
refers to the immediate parent class object. It is used to call superclass
methods, constructors, and variables. It helps avoid ambiguity between
parent and child members. Subclasses can extend functionality by
adding new methods or overriding existing ones. Constructors of parent
class are invoked using `super()`.
3. Method Overriding
Method overriding occurs when a subclass provides its own
implementation of a method already defined in the superclass. It must
have the same method signature (name, parameters, return type). It
supports runtime polymorphism. Access modifiers can be same or less
restrictive. It is annotated using `@Override` for clarity. It allows
dynamic method dispatch at runtime.
**Example:**
```java
class Animal {
void sound() { [Link]("Animal sound"); }
}
class Dog extends Animal {
@Override
void sound() { [Link]("Dog barks"); }
}
```
4. Object Class
The `Object` class is the root of all classes in Java. Every class implicitly
inherits from it. It provides important methods such as `toString()`,
`equals()`, `hashCode()`, `clone()`, and `finalize()`. These methods can
be overridden to provide custom behavior. It ensures consistency across
Java programs. It belongs to the `[Link]` package which is
automatically imported.
5. Polymorphism
Polymorphism means “many forms”. It allows a method or object to
behave differently in different situations. There are two types: compile-
time (method overloading) and runtime (method overriding). It improves
flexibility and code reusability. It is achieved through inheritance and
interfaces. It is widely used in real-world applications.
6. Dynamic Binding
Dynamic binding refers to linking method calls with method definitions
at runtime instead of compile time. It is associated with overridden
methods. JVM decides which method to call based on the object type. It
enables runtime polymorphism. It provides flexibility but slightly
impacts performance.
7. Generic Programming
Generics allow classes and methods to work with different data types. It
ensures type safety and eliminates the need for casting. It is
implemented using `<T>` syntax. It improves code reusability and
readability. It is widely used in collections framework.
**Example:**
```java
class Box<T> {
T value;
void set(T value) { [Link] = value; }
T get() { return value; }
}
```
8. Casting Objects
Casting is the process of converting one object type into another.
Upcasting (child to parent) is automatic and safe. Downcasting (parent
to child) must be done explicitly. Incorrect casting leads to
`ClassCastException`. It is useful in polymorphism. Always use
`instanceof` before downcasting.
9. instanceof Operator
The `instanceof` operator checks whether an object belongs to a
particular class. It returns true or false. It is mainly used to avoid runtime
errors during casting. It ensures safe type conversion. It is commonly
used in polymorphic code.
**Example:**
```java
if(obj instanceof Dog) {
Dog d = (Dog)obj;
}
```
10. Abstract Class
An abstract class cannot be instantiated. It may contain abstract methods
(without body) and concrete methods. It is declared using `abstract`
keyword. Subclasses must implement abstract methods. It provides
partial abstraction. It is useful when some common behavior is shared.
11. Interface in Java
An interface is a blueprint of a class. It contains abstract methods and
constants. It supports multiple inheritance. Methods are public by
default. Java 8 introduced default and static methods. It helps achieve
full abstraction. Classes implement interfaces using `implements`
keyword.
12. Package in Java
A package is a collection of related classes and interfaces. It helps
organize code and avoid naming conflicts. It improves code
maintainability. Packages are created using `package` keyword. Java
provides built-in packages like `[Link]`, `[Link]`.
13. [Link] Package
The `[Link]` package contains utility classes like ArrayList, HashMap,
Scanner, Date. It provides data structures and algorithms. It is part of
Java Collections Framework. It simplifies data handling. It is widely
used in real-world applications.
EVENT AND GUI PROGRAMMING
14. Event Handling in Java
Event handling is the process of responding to user actions like button
clicks or key presses. It follows the delegation event model. It involves
event source, event object, and event listener. Listeners are interfaces
implemented by classes. It makes GUI interactive.
15. Event Types
Java provides various event types such as ActionEvent, MouseEvent,
KeyEvent, WindowEvent. Each represents a specific user action. They
belong to `[Link]` package. Proper handling ensures smooth
interaction.
16. Mouse and Key Events
Mouse events include click, press, release, enter, exit. Key events
include key pressed, released, and typed. They are handled using
MouseListener and KeyListener. These interfaces must be implemented.
17. GUI Basics
GUI stands for Graphical User Interface. It allows users to interact using
graphical components. Java uses AWT and Swing for GUI development.
GUI applications are event-driven. Components are placed inside
containers.
18. Panels and Frames
Frame is a top-level container used as main window. Panel is used to
organize components inside a frame. Frames are created using `JFrame`.
Panels help structure layout.
19. Layout Managers
Layout managers control the arrangement of components.
- FlowLayout: Left to right
- BorderLayout: Five regions
- GridLayout: Rows and columns
20. GUI Components
Components include buttons, labels, text fields, etc. They enable user
interaction. They are added to containers like frames and panels.
21. Buttons, Checkboxes, Radio Buttons
Buttons perform actions. Checkboxes allow multiple selections. Radio
buttons allow only one selection using ButtonGroup. They are widely
used in forms.
22. Labels, TextFields, TextAreas
Labels display text. TextFields accept single-line input. TextAreas
accept multi-line input. They are basic input/output components.
23. ComboBox, Lists, ScrollBars, Sliders
ComboBox provides dropdown list. Lists display multiple items.
ScrollBars allow navigation. Sliders help select a value within range.
24. Windows, Menus, Dialog Box
Windows act as main containers. Menus provide options like File, Edit.
Dialog boxes show messages or take input. They improve user
interaction.
25. Applet and Life Cycle
Applet is a small Java program embedded in browser (now obsolete).
Life cycle includes:
- init()
- start()
- stop()
- destroy()
It was used for web-based Java programs.
26. Introduction to Swing
Swing is an advanced GUI toolkit. It provides rich components like
JButton, JFrame, JTextField. It is platform-independent. It follows MVC
architecture. It is preferred over AWT.
**Example:**
```java
import [Link].*;
class MyFrame {
public static void main(String[] args) {
JFrame f = new JFrame("My App");
JButton b = new JButton("Click Me");
[Link](100,100,100,40);
[Link](b);
[Link](300,300);
[Link](null);
[Link](true);
}
}
```
I/O PROGRAMMING AND COLLECTIONS
27. Text and Binary I/O
Text I/O deals with reading and writing data in human-readable form
such as characters and strings. It uses character streams like Reader and
Writer classes. Binary I/O handles data in raw binary format (bytes)
using InputStream and OutputStream. Text I/O is easier to debug, while
binary I/O is more efficient and compact. Choice depends on application
needs such as readability vs performance. Both support file handling in
Java.
**Example (Text I/O):**
```java
import [Link].*;
class TextIOExample {
public static void main(String[] args) throws Exception {
FileWriter fw = new FileWriter("[Link]");
[Link]("Hello Java");
[Link]();
}
}
```
28. Binary I/O Classes
Binary I/O uses byte streams to read/write raw data. Important classes
include FileInputStream and FileOutputStream. They are used for
images, audio, and other non-text files. BufferedInputStream and
BufferedOutputStream improve performance. DataInputStream and
DataOutputStream allow reading/writing primitive data types. These
classes provide efficient low-level I/O operations.
**Example:**
```java
import [Link].*;
class BinaryIOExample {
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("[Link]");
[Link](65);
[Link]();
}
}
```
29. Object I/O
Object I/O allows reading and writing objects to files using serialization.
Classes must implement Serializable interface. ObjectOutputStream
writes objects, and ObjectInputStream reads them. It preserves object
state. It is used in saving application state and data transfer.
Deserialization reconstructs objects from file.
**Example:**
```java
import [Link].*;
class Student implements Serializable {
int id; String name;
Student(int id, String name) { [Link] = id; [Link] = name; }
}
class ObjectIOExample {
public static void main(String[] args) throws Exception {
ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream("[Link]"));
[Link](new Student(1, "Aman"));
[Link]();
}
}
```
30. Random Access Files
RandomAccessFile allows reading and writing at any position in a file.
It does not follow sequential access. It supports both read and write
operations. Methods like seek() are used to move file pointer. It is useful
in database systems and large file manipulation. It improves flexibility in
file handling.
**Example:**
```java
import [Link].*;
class RandomAccessExample {
public static void main(String[] args) throws Exception {
RandomAccessFile raf = new RandomAccessFile("[Link]", "rw");
[Link]("Hello");
[Link](0);
[Link]([Link]());
[Link]();
}
}
```
31. Introduction to Java Collections
Java Collections Framework (JCF) provides classes and interfaces to
store and manipulate data. It includes lists, sets, and maps. It reduces
programming effort by providing ready-made data structures. It ensures
high performance and scalability. It is part of [Link] package.
Collections support dynamic memory allocation.
32. Overview of Java Collection Framework
JCF consists of interfaces like List, Set, Map and classes like ArrayList,
HashSet, HashMap. It also includes algorithms like sorting and
searching. It provides iterators for traversal. It supports generic
programming. It improves code reusability and efficiency. It is widely
used in enterprise applications.
33. ArrayList
ArrayList is a dynamic array implementation of List interface. It allows
duplicate elements. It maintains insertion order. It provides fast random
access. It is not synchronized. It is widely used due to flexibility.
**Example:**
```java
import [Link].*;
class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
[Link]("A"); [Link]("B");
[Link](list);
}
}
```
34. Vector
Vector is similar to ArrayList but synchronized. It is thread-safe. It was
part of legacy classes. It is slower than ArrayList due to synchronization
overhead. It allows duplicate elements. It maintains order.
35. Hashtable
Hashtable stores key-value pairs. It does not allow null key or value. It is
synchronized and thread-safe. It is part of legacy collection classes. It is
slower compared to HashMap. It uses hashing technique.
36. Stack
Stack follows LIFO (Last In First Out) principle. It extends Vector class.
It provides methods like push(), pop(), peek(). It is used in recursion,
parsing, and undo operations. It is simple and widely used.
**Example:**
```java
import [Link].*;
class StackExample {
public static void main(String[] args) {
Stack<Integer> s = new Stack<>();
[Link](10); [Link](20);
[Link]([Link]());
}
}
```