Object Oriented Programming

Question 1:

Inheritance is a core concept of Object-Oriented Programming (OOP) where one class (child) can use the properties and methods of another class (parent).

Types of Inheritance:

  1. Single Inheritance – One child from one parent

  2. Multilevel Inheritance – Chain of inheritance

  3. Hierarchical Inheritance – Multiple children from one parent

  4. Multiple Inheritance – One class inherits from multiple (using interfaces in Java)

  5. Hybrid Inheritance – Combination of types above

// Parent class
class Animal {
    void speak() {
        System.out.println("Animal speaks");
    }
}

// Child class
class Dog extends Animal {
    void bark() {
        System.out.println("Dog barks");
    }
}

// Main class
public class Main {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.speak(); // Inherited from Animal class
        d.bark();  // Defined in Dog class
    }
}

Question 2 :

Inheritance Hierarchy is a tree-like structure formed when multiple classes inherit from one or more base classes.


class Animal {

    void speak() {

        System.out.println("Animal speaks");

    }

}


class Dog extends Animal {

    void bark() {

        System.out.println("Dog barks");

    }

}


class Cat extends Animal {

    void meow() {

        System.out.println("Cat meows");

    }

}

        Animal
        /    \
  Dog    Cat

Quesion : 3

A class is a blueprint or template that defines properties (variables) and behaviors (methods) of an object.

An object is a real instance of a class. It has actual values and can use the class methods.


Quesion : 4


What is a Method?

A method is a block of code that performs a specific task.
For example, a method named greet() might just print “Hello”.

What is Method Overloading?

Method Overloading means having multiple methods with the same name but different parameters (either number or type).


class Demo {

    void greet() {

        System.out.println("Hello!");

    }


    void greet(String name) {

        System.out.println("Hello, " + name);

    }

}


Abstraction: 

 abstract class mobileUser{

    abstract void sendMessage();

}


 class Rahim extends mobileUser{

    @Override

    void sendMessage(){

        System.out.println("Hello I am Rahim");

    }

}


 class Karim extends mobileUser{

    @Override

    void sendMessage(){

        System.out.println("Hello I am Karim");

    }

}


class Main {

    public static void main(String[] args) {

    mobileUser mu;

    mu = new Rahim();

    mu.sendMessage();

    mu = new Karim();

    mu.sendMessage();

    }

}

Post a Comment

0 Comments

Layout Inflater