UNIT 1:

Inheritance :

Single , Multi Level , Hierarchical Inheritance:


// base class 
class Animal {
    void eat() {
        System.out.println("eating...");
    }
}

// intermediate 1 class
class Dog extends Animal {
    void bark() {
        System.out.println("barking...");
    }
}

// intermediate 2 class
class Cat extends Animal {
    void meow() {
        System.out.println("meowing...");
    }
}

// derived class
class Puppy extends Dog {
    void weep(){
        System.out.println("weeping...");
    }
}

public class Inheritance {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.bark();
        dog.eat();

        Cat cat = new Cat();
        cat.meow();
        cat.eat();
    }
}

Hybrid Inheritance:


interface Animal {
    void eat();
    void travel();
}

interface Pet {
    void play();
}

class Dog implements Animal, Pet {
    public void eat() {
        System.out.println("Dog is eating");
    }
    public void travel() {
        System.out.println("Dog is travelling");
    }
    public void play() {
        System.out.println("Dog is playing");
    }
}

public class Hybrid {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat();
        dog.travel();
        dog.play();
    }
}

Exception Handling

having all the keywords {try , catch , throw , throws , finally } and also custom exception as well.

import java.lang.Exception;
import java.lang.ArrayIndexOutOfBoundsException;
class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}

public class ExceptionHandling {
    // method that throws an custom exception
    public static void checkNumber(int number) throws CustomException {
        if (number < 0) {
            throw new CustomException("Number cannot be negative");
        }
    }

    public static void main(String[] args) {
        try{
            int arr[] = {1,2,3,4,5};
            System.out.println(arr[10]);
            checkNumber(-1);
        }catch(ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index out of bounds "+ e.getMessage());
        }catch(CustomException e) {
            System.out.println("Custom exception "+ e.getMessage());
        }catch(Exception e) {
            System.out.println("Exception "+ e.getMessage());
        }finally {
            System.out.println("Finally block");
        }

        try {
            checkNumber(-1);
        }catch(CustomException e) {
            System.out.println("Custom exception "+ e.getMessage());
        }

    }
}

Connection to Server