Interview questions on inheritance
Questions on inheritance
1)What do you mean by inheritance.?
Through inheritance, a class (Sub Class) can inherit properties of another class (Super Class).
What are the types of inheritance?
There are 5 types of inheritance.
1). Single Inheritance : One class is extended by only one class.
2). Multilevel Inheritance : One class is extended by a class and that class in turn is extended by another class thus forming a chain of inheritance.
3). Hierarchical Inheritance : One class is extended by many classes.
4).Hybrid Inheritance : It is a combination of above types of inheritance.
5). Multiple Inheritance : One class extends more than one classes. (Java does not support multiple inheritance.)
Can a class extend more than one classes or does java support multiple inheritance? If not, why?
No, a class in java can not extend more than one classes or java does not support multiple inheritance. To avoid ambiguity, complexity and confusion, java does not supports multiple inheritance. For example, If Class C extends Class A and Class B which have a method with same name, then Class C will have two methods with same name. This causes ambiguity and confusion for which method to use. To avoid this, java does not supports multiple inheritance.
Are constructors and initializers also inherited to sub classes.?
No, Constructors and initializers are not inherited to sub classes. But, they are executed while instantiating a sub class.
What happens if super class and sub class, have a field with same name?
Super class field will be hidden in the sub class. You can access hidden super class field in sub class using super keyword.
Are static members inherited to sub classes?
Yes, Static members are inherited to sub classes.
How do you restrict a member of a class from inheriting to it’s sub classes.?
By declaring that member as a private. Because, private members are not inherited to sub classes
Comments
Post a Comment