UNIT 4 JAVA

PROGRAMMING WITH JAVA


UNIT 4

  • Inheritance, Interfaces and Packages

BASICS OF INHERITANCE

  • Definition:
    • Inheritance is a fundamental concept in OOP that allows a subclass to inherit properties (attributes and methods) from a superclass.
    • Represents the IS-A relationship (parent-child relationship).

Terms Used in Inheritance

  • Class:
    • A group of objects with common properties; a template for creating objects.
  • Subclass/Child Class:
    • A class that inherits from another class; also known as derived class, extended class.
  • Superclass/Parent Class:
    • The class that a subclass inherits features from; also known as base class.
  • Reusability:
    • Mechanism allowing re-use of fields and methods of the existing class for new class creation.

Java Inheritance Syntax

  • Syntax:
  class SubclassName extends SuperclassName {
      // methods and fields
  }
  ```
- The **extends** keyword indicates that a new class derives from an existing class, adding functionality.

---

## TYPES OF INHERITANCE

### Single Inheritance
- **Definition**:
  - Occurs when a class inherits from another class.

### Example:

java class Animal { void eat() { System.out.println("eating…"); } } class Dog extends Animal { void bark() { System.out.println("barking…"); } } class TestInheritance { public static void main(String args[]) { Dog d = new Dog(); d.bark(); d.eat(); } } // Output: barking… eating…

### Multilevel Inheritance
- **Definition**:
  - Involves a chain of inheritance, where at least two classes are in the hierarchy.

### Example:

java class Animal { void eat() { System.out.println("eating…"); } } class Dog extends Animal { void bark() { System.out.println("barking…"); } } class BabyDog extends Dog { void weep() { System.out.println("weeping…"); } } class TestInheritance2 { public static void main(String args[]) { BabyDog d = new BabyDog(); d.weep(); d.bark(); d.eat(); } } // Output: weeping… barking… eating…

### Hierarchical Inheritance
- **Definition**:
  - Occurs when two or more classes inherit from a single superclass.

### Example:

java class Animal { void eat() { System.out.println("eating…"); } } class Dog extends Animal { void bark() { System.out.println("barking…"); } } class Cat extends Animal { void meow() { System.out.println("meowing…"); } } class TestInheritance3 { public static void main(String args[]) { Cat c = new Cat(); c.meow(); c.eat(); // c.bark(); // Compile Time Error } }

### Multiple Inheritance
- **Note**:
  - Not supported in Java due to complexity; ambiguity may arise if two parent classes have the same method.

### Hybrid Inheritance
- **Definition**:
  - Combination of more than two types of inheritance (single and multiple), achievable only via interfaces.

---

## Method Overriding in Java
- **Definition**:
  - When a subclass has the same method as the parent class.
- **Purpose**:
  - To provide specific implementation of a method defined in a superclass.
  - Used for runtime polymorphism.

### Rules for Method Overriding:
1. Method names must be the same as in the parent class.
2. Parameters must be the same as in the parent class.
3. There must be an IS-A relationship (inheritance).

### Example:

java class Vehicle { void run() { System.out.println("Vehicle is running"); } } class Bike2 extends Vehicle { void run() { System.out.println("Bike is running safely"); } public static void main(String args[]) { Bike2 obj = new Bike2(); obj.run(); } } // Output: Bike is running safely

---

## Extending Classes in Java
- **Definition**:
  - The keyword **extends** indicates inheritance between child and parent class.
- **Syntax**:

java class ChildClass extends ParentClass { … }   ```

  • When a child class extends a class, it inherits properties of the parent class.

Defining Interfaces in Java

  • Definition:
    • An interface is a blueprint of a class containing static constants and abstract methods (no method body).
  • Syntax:
  interface <interface_name> {
      // declare constant fields
      // declare abstract methods
  }
&nbsp;&nbsp;```

### Example:

java interface Printable { void print(); } class A6 implements Printable { public void print() { System.out.println("Hello"); } public static void main(String args[]) { A6 obj = new A6(); obj.print(); } } // Output: Hello

---

## Differences Between Class and Interface
| **Aspect** | **Class** | **Interface** |
| ----------- | --------- | -------------- |
| Keyword     | class     | interface      |
| Instantiation| Yes      | No             |
| Inheritance | Can inherit from another class | Cannot inherit a class |
| Constructors | Can have constructors | Cannot have constructors |
| Access Specifiers | Support any access specifiers | Methods and variables are public by default |

---

## Implementing Interfaces
- **Definition**:
  - Use the **implements** keyword to declare that a class implements an interface. 
- **Functionality**:
  - The implementing class provides the body for the abstract methods defined in the interface.

### Multiple Inheritance Using Interfaces
- **Definition**:
  - A class can implement multiple interfaces, enabling multiple inheritance.
- **Example**:

java interface Printable { void print(); } interface Showable { void show(); } class A7 implements Printable, Showable { public void print() { System.out.println("Hello"); } public void show() { System.out.println("Welcome"); } public static void main(String args[]) { A7 obj = new A7(); obj.print(); obj.show(); } } // Output: Hello Welcome

---

## Abstract Class in Java
- **Definition**:
  - An abstract class may contain abstract and non-abstract methods and cannot be instantiated.
- **Requirements**:
  - Must be declared with the **abstract** keyword and can include constructors and static methods.

### Example of Abstract Class:

java abstract class A {} abstract class Bike { abstract void run(); } class Honda4 extends Bike { void run() { System.out.println("running safely"); } public static void main(String args[]) { Honda4 obj = new Honda4(); obj.run(); } } // Output: running safely

---

## Final Class in Java
- **Definition**:
  - A final class cannot be subclassed; it prevents inheritance.
- **Use Cases**:
  - Ensure behavior remains unaltered, create immutable objects, or ensure security.

### Example of Final Class:

java final class Calculator { public int add(int a, int b) { return a + b; } } class AdvancedCalculator extends Calculator { public int subtract(int a, int b) { return a - b; } // This will cause a compile-time error because Calculator is final } ```


Packages in Java

  • Definition:
    • A package is a collection of similar classes and interfaces, categorized into built-in and user-defined packages.
  • Importing a Package:
    • Syntax: import packageName;
  • Example:
    • import java.util.*;
Built-in Packages:
  • java.lang: Basic language support (e.g. primitive data types).
  • java.util: Utility classes, data structures, and date/time operations.
  • java.io: Classes for input/output operations.
User-defined Packages:
  • Process:
    • Create a directory named after the package, e.g., myPackage, and define classes inside it.

Access Rules for Packages

  • Public:
    • Accessible from anywhere.
  • Private:
    • Accessible only within the same class.
  • Protected:
    • Accessible within the same package and via inheritance.
  • Default (No Specifier):
    • Accessible only within the same package.
Accessing Rules Summary:
Access ModifierWithin ClassWithin PackageSubclassesOutside Package
PrivateYesNoNoNo
DefaultYesYesNoNo
ProtectedYesYesYesNo
PublicYesYesYesYes

THANK YOU