Q:

Inheritance Code reusability

1:
class arbitrary {
    void print() {
        System.out.println("Hello Inheritance");
    }
}
public class inheritance extends arbitrary {
    public static void main(String args[]) {
        arbitrary ar = new arbitrary();
        ar.print();
    }
}

Outputs: Hello Inheritance
2:
class arbitrary {
    void print() {
        System.out.println("Hello Inheritance");
    }
}
public class inheritance extends arbitrary {
    public static void main(String args[]) {
        inheritance in = new inheritance(); in .print();
    }
}

Outputs: Hello Inheritance
3:
class arbitrary {
    void print() {
        System.out.println("Hello Inheritance");
    }
}
public class inheritance {
    public static void main(String args[]) {
        arbitrary ar = new arbitrary();
        ar.print();
    }
}

Outputs: Hello Inheritance
4:
class arbitrary {
    void print() {
        System.out.println("Hello Inheritance");
    }
}
public class inheritance {
    public static void main(String args[]) {
        inheritance in = new inheritance(); in .print();
    }
}

Outputs: Error 
1st and 2nd programs uses the concept of inheritance and re-usability, but in the 3rd program the base class (i.e. inheritance) not extends the superclass (i.e. arbitrary) still it is running successfully .
So without extending how it is possible to reuse the code from superclass? can any one help me to figure out that how the 3rd program is able to run successfully without using the concept of inheritance and re-usability.

A:

Your first and third programs are actually the same.
It doesn't really matter what the Inheritance class is extending, because you are not really using it. Your main is using only the Arbitrary class, and since the Arbitrary class has a print method, it succeeds and prints the message.
Your second example works because Inheritance extends Arbitrary, and you are using the Inheritance class for your object. Since it extends Arbitrary, it has all the methods of Arbitrary, and therefore has print and will print successfully.
But your forth example uses an Inheritance object. But despite its name, it does not extend Arbitrary, and has no methods other than main, meaning it also doesn't have a print method. Hence the error.
Your confusion perhaps stems from:

Your belief that program 1 demonstrates inheritance. It doesn't, really. You are not using the extended class so there is no inheritance in use.
Your belief that 3 and 4 have the same logic. They don't. Your 3rd is using the Arbitrary class that has a print method, but your 4th is using the Inheritance class, which doesn't have a print method.

