Lecture 11 and 12- Inheritance, Method overriding, Constructor, Object class Flashcards
What does inheritance stand for in OOP?
In OO languages, classes can be derived from other classes, thereby inheriting fields and methods from those classes.
Java only supports single inheritance - each subclass can have one and only one direct super-class.
explain super class and subclass ?
Superclass or base, parent class Subclass or derived, child, extended class
What is the benefit of inheritance in OOP?
Code re-usability;
Better program structure.
What are the 4 areccess modifiers?
private
default
protected
public
Who can inherit by a private superclass?
any subclass whithin that superclass
What subclass can inherit from a default superclass?
Any subclass is in the same package as its parent, it also inherits the default (or package-private) attributes and methods of the parent.
When can a subclass inherit from a public or protected superclass?
A subclass inherits all of the public and protected attributes and methods of its parent as well as all its ancestors, no matter what package the subclass is in.
What can a subclass do apart from inheriting ?
add its own attributes and methods.
add same-signature methods - method overriding.
add same-name attributes (but not recommended) -
attribute hiding .
What is method overriding ?
A subclass defines a method which has the same name, number and type of parameters, and return type as a method in the superclass.
Recall Method overloading: If a class has multiple methods having the same name but different in parameters.
When overriding a method, it is recommended to use the @Override annotation, though it is optional.
What is a must for an overriding method ?
The access modifier for an overriding method can allow more, but not less, access than the overridden method.
Are constructors inherited ?
Constructors are not inherited. Each class defines its own constructors.
But the constructor of the super-class can be invoked from the subclass, using super().
When can the final keyword be used ?
A final attribute: it is a constant.
final int MAX BORROW BOOKS = 5;
A final method: we can not override this method.
final void eat(){…}
A final class: we can not extend it.
public final class String {...}//String class doesn’t have any subclasses
What is finally used for?
try-catch-finally
What is upcasting ?
Upcasting: assign a subclass instance to a superclass reference.
Animal d=new Dog(“black”,5,10); //upcasting
You can invoke all the methods defined in the Animal class
d. eat();//the superclass’s method
d. sleep();//the subclass’s version is invoked.
You CANNOT invoke methods defined in the Dog class for the reference d.
What is downcasting ?
Downcasting: revert a substituted instance back to a subclass reference.