Q) Which inheritance in java programming is not supported
- Multiple inheritance using classes
- Multiple inheritance using interfaces
- Multilevel inheritance
- Single inheritance
Answer: 1
NOTE: Java does not support multiple inheritance of classes but it supports multiple inheritance for interfaces. Means, a class cannot inherit more than one class but it can inherit and implement multiple interfaces.
Q) What is subclass in java?
- A subclass is a class that extends another class
- A subclass is a class declared inside a class
- Both above.
- None of the above.
Answer: 1
A subclass is a class that extends another class. In other words, subclass inherits the functionality of the class it extends. See below example.
class BaseClass {
public void foo() {
System.out.println("Base class");
}
}
//This is a subclass that inherit
//public methods of base class
class SubClass extends BaseClass {
}
public class Program {
public static void main(String[] args) {
SubClass s = new SubClass();
s.foo();
}
}
Output:
Base class
Q) If class B is subclassed from class A then which is the correct syntax
- class B:A{}
- class B extends A{}
- class B extends class A{}
- class B implements A{}
Answer: 2
Below is the example.
class A{
}
//Class B is sub classed from class A
class B extends A{
}
Q) Order of execution of constructors in Java Inheritance is
- Base to derived class
- Derived to base class
- Random order
- none
Answer: 1
On object creation of derived class, first base class constructor and then derived class constructor will be called.
Below is the java code example
class Animal{
public Animal(){
System.out.println("Base Constructor");
}
}
class Cat extends Animal{
public Cat(){
System.out.println("Derived Constructor");
}
}
public class Program {
public static void main(String[] args) {
Cat c = new Cat();
}
}
Output
Base Constructor
Derived Constructor