Java Inheritance


1. What is an interface in Java?

Interface is a group of methods with empty body. A class implementing an interface has to define these methods.

e.g.
OnClickListener is an interface with a method onClick()

interface OnClickListener(){
public void onClick();
}

Now any class which defines this interface has to define onClick() method.

class MyClass implements OnClickListener{
....
public void onClick()
{
....
}
}


2. What are overloading and overriding?

When multiple methods in the same class have same name but different type/number of parameters, the methods are said to be overloaded.

When a method of a base class is redefined in a derived class with same signature, it is said to be overriding the base class method.

e.g.
class A{
int sum(int a,int b){.....}
float sum(float a,float b){....}
int sum(int a,int b,int c, int d){....}
}


class A{
void print(int a){.....}
}
class B extends A{
void print(int a){.....}
}


3. Can you override final methods?

No. Final methods can not be overridden. By defining a method as final, subclasses can not override that method.

It is advisable to make the methods called by constructor as final.


4. What is an abstract class? How does it differ from an interface?

An abstract class is a class which can not be instantiated - no objects can be created from an abstract class. An abstract class is defined with keyword abstract.

But a sub-class of an abstract can be instantiated.

An abstract class can have fields, methods. The methods can be abstract or non-abstract.

e.g.

abstract class Vehicle{
int speed;
void start(){}
abstract void accelerate();
}

If you define an abstract method in a class, then the class must be declared as abstract. Otherwise you will get a syntax error.

An interface can only have final fields and abstract methods. No method in an interface can have an implementation. And an interface can have only final, static, public fields.

A class can extend one abstract class. But a class can implement multiple interfaces.


5. What is inheritance? Explain with an example.

Inheritance is the process of creating new classes extending existing classes. The new class is called sub-class or derived class and the original class is called base class.
The inherited class inherits all the methods and fields of the base class. It can also its own members.

Every object of a derived class is an object of base class.


6. With an example explain the keyword super.

super keyword is used to call the super class method.

When a method is overridden by a derived class, the base class method is hidden. To call the base class method, we have to use super. followed by method name.

e.g.
class B1{
void print(){
System.out.println("B1");
}
}
class D1 extends B1{
void print(){
System.out.println("D1");
super.print();
}
}
class Test{
public static void main(String args[]){
D1 obj = new D1();
obj.print();
}
}

Now print() method in D1 class calls the super class print method.

Output of the program
D1
B1

super keyword is also used to call the super class constructor in a derived class constructor.

super() call in a constructor must be first statement of the constructor.

class B1{
B1(){
System.out.println("Constructor of B1");
}
}
class D1 extends B1{
D1(){
super();
System.out.println("Constructor of D1");
}
}

Now if we create an object of D1 class, then it will call D1 constructor which also calls B1 constructor.

If we do not explicitly call super class constructor, compiler implicitly calls super class constuctor always. (which calls its super class constructor and so on. It is called constructor chaining. )


7. Which is the base class in Java for all other classes

Object is the base class of all other classes in Java.

All classes in Java are either directly or indirectly derived from Object class.

Object class provides the following methods - toString(), equals(), hashCode(), finalize, clone() and getClass() methods.


8. What is final class?

A class which can not be subclassed is a final class. A class is made final by add the keyword final to the definition of the class.

final class A{
int m;
}
class B extends A{
..
}

Defintion of class B gives an error.

e.g.
String library class is a final class.


9. Write a program with an interface which has a method to find perimeter. Write two classes circle and rectangle which implement this interface

interface Calc{ 
    public int findPerimeter();
}
class Circle implements Calc{
    int radius;
    final double PI=22.0/7;
    Circle(int n){
      radius=n;
    }
    public int findPerimeter(){
       return (int)(2*PI*radius);
    }
}
class Rectangle implements Calc{
   int len,wid;
   Rectangle(int l,int w){
      len=l;
      wid = w;
   }
   public int findPerimeter(){
      return 2*(len+wid);
   }
}

class Demo{
     public static void main(String args[]){
          Circle c = new Circle(7);
          Rectangle r = new Rectangle(10,5);
          System.out.println("Perimeter of circle is "+c.findPerimeter());
          System.out.println("Perimeter of rectangle is "+r.findPerimeter());
    }
}

10. How do you inherit from a class in Java?

A class is inherited by using the keyword extends.

e.g.
class B extends A{
/****
}

A class can inherit only from one super class.

The inherited class inherits all the instance members of the super class. The sub class can access all the default, public and protected members of super class. But it can not access the private members of the super class.


11. What is method overriding? What are the rules for overridden methods?

 

Overriding a method is redefining a super class method in the sub class.

The overriding method must have the exact same signature as the super class method.


12. Is it possible to override a static method in Java?

No. It is not possible to override a static method. If we write a static method in subclass with the same signature as super class, then the super class method is hidden. And more importantly there is no late binding or polymorphism.

class A{
int n;
void print(){
System.out.println(" n is"+n);
}
static void printHello(){
System.out.println("Hello coder!!");
}
}
class B extends A{
static void printHello(){
System.out.println("Hello Java");
}
}
class Test{
public static void main(String args[]){
B obj = new B();
obj.print();
obj.printHello();
}
}

Output is
n is0
Hello Java

Here we are not able to call the base class printHello() method as it is hidden.



13. Can an interface extend another interface? Can an interface extend multiple interfaces?

Yes. An interface can extend one or more interfaces.

interface car extends vehicle, fourwheeler{
/****/
}


14. Write a program with an interface compute with two methods add and subtract. Define PI as constant member of this interface. Write a class which implements this interface

import java.util.Scanner;

interface Compute{
    int add(int a,int b);
    int subtract(int a,int b);
    double PI=(double)22/7;
}
public class InterfaceTest implements Compute{
    public int add(int a, int b) {
        return a+b;
    }

    public int subtract(int a, int b) {
        return a-b;
    }
    public static void main(String args[]){
        int m,n;
        InterfaceTest obj = new InterfaceTest();
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter two numbers");
        m = scanner.nextInt();
        n = scanner.nextInt();
        System.out.println("The sum is "+obj.add(m,n));
        System.out.println("Enter radius of circle");
        int r = scanner.nextInt();
        System.out.println("The area of circle is "+obj.PI*r*r);
    }
}

15. What are default methods? How do you define them?

Methods declared in an interface with the keyword default are default methods. Such methods must have implementation.

Normal methods in an interface do not have implementation and are abstract. Default methods are not abstract.

e.g.
interface MyInterface{
void aMethod();
default void defMethod(){
System.out.println("Hello user");
}
}


16. Write a class TwoWheeler which in inherited from class Vehicle.

class Vehicle{
     int speed;
     void start(){}
     void stop(){}
}
class TwoWheeler extends Vehicle{}

public class Demo{
   public static void main(String args[]){
       TwoWheeler t = new TwoWheeler;
       t.speed = 40;
       t.start();
  }
}

The TwoWheeler class has inherited all fields and methods of Vehicle class.

17. Which of the following lines of code will produce syntax error? Why?

class A{
   int num1;
}
class B extends A{
   int num2;
}
class Demo{
    public static void main(String args[]){
          A a1 = new A();
          B b1 = new B();
          b1.num1 = 10;//line 1
          b1.num2 = 20;//line 2
          a1.num1 = 5;//line 3
          a1.num2 = 15;//line 4
          a1 = new B();//line 5
          b1 = new A();//line 6
    }
}

Lines 4 and 6 produce error.

b1 is an object of class B. B class has two fields - num1 which is inherited from A class and num2 which is a field from B class. b1 can access both of them.

If num1 was a private field, then b1 will not be able to access num1. But as there is no access speicifer - num1 is having default access - which means it is accessible in the package where it is defined.

But a1 is an object of A class. And as A class is a super class object, it has only one field num1. It does not have the field num2. So line 4 produces error.

A derived class object can be assigned to a base class object. But the reverse is not true.

Any object of B class is also an object of A class. But an object of A class is not an object of B class.


18. Explain final classes with an example.


If a class is defined as final, it can not be extended. Final classes are useful in creating immutable classes - String library class is a final class.

If you extend a final class, you will get a syntax error.

e.g.
final class A{
int n;
void print(){
System.out.println("Hello world");
}
}
class B extends A{//syntax error
int m;
}