Review of inheritance, polymorphism, and interfaces
- In Java inheritance, the subclass is derived from only one existing
class, called superclass.
- The private members of a superclass are private to subclass. The subclass
cannot directly access them.
- A subclass can override the methods of a superclass. However, this
overriding applies only to the objects of the subclass.
- No final or static methods can be overridden.
- If a class is declared as final, it cannot be extended by a
subclass.
- If the subclass overrides a public method of a superclass, one can call
the corresponding superclass method by using the reserved word super
followed by the dot operator followed by the method name with an appropriate
parameter list.
- While designing a superclass constructor, a call to the superclass
constructor is specified by using the reserved word super followed by
the parameters list. Moreover, the call of the superclass constructor must be
the first statement.
- For a superclass to give a member access to its subclass and prevent its
direct access outside the class, you must give the protected access
to the member.
- If you define a class and do not use the reserved word extends to
derive it from an existing class, then your class is automatically considered
to be derived from class Object. The class Object directly or
indirectly becomes the superclass of every class in Java.
- Object variables are polymorphic. Java allows to treat an object
of a subclass as an object of a superclass. That is, a reference variable
of a superclass type can point to an object of subclass type.
- You cannot automatically make a reference variable of a subclass type
point to an object of superclass type. Use casting (with caution!).
- An abstract method is a method that has only the heading but no body. The
heading of an abstract method is terminated with a semicolon.
- An abstract class is a class declared with the reserved word
abstract
- An abstract class can contain instance variables, constructors,
finalizer, and non-abstract methods.
- An abstract class can contain abstract methods.
- If a class contains an abstract method, the class has to be declared as
abstract.
- You cannot instantiate an object of an abstract class type. You can
only declare a reference variable of an abstract class type.
- An interface is a class that contains only abstract methods and/or
named constants.
- You do not instantiate interfaces, one implements them instead. To
implement an interface, you must provide implementations to all its
methods.
- Java allows a class to implement several interfaces.
- Use the Java interfaces to share common behavior. Use the inheritance to
share common code.