Java Reference
In-Depth Information
2. Use
extends
when inheriting from a class and
implements
when inheriting from an
interface.
3. An abstract method is a method without a body. This method must be overridden in
any non-abstract subclasses with full body.
4. An abstract class is similar to a regular class, but it cannot be instantiated. Conversely,
an interface has no variables other than constants and only abstract methods.
5. Java allows us to inherit from one class and from multiple interfaces.
6. The
Object
class is the superclass of all classes.
7.
o1.m()
results in calling exactly one of potentially several methods. The runtime type
of the
o1
object is determined. Then Java searches for the
m
method in this type and
its ancestors in the inheritance hierarchy and executes the first method that it finds.
8. An object can be automatically cast to an object of type of the superclass of the
object. However, one needs an explicit cast to convert an object to an object of one
of the subclasses.
9. We need to implement the
Cloneable
interface and override the
clone
method as
public
in order to use it. The
clone
method should also be designed to handle an ex-
ception of type
CloneNotSupportedException
. When overriding the
clone
method,
we need to make sure that the inner objects are properly cloned using deep copy.
The default
clone
method in the
Object
class only copies the addresses of the inner
objects, that is, it performs shallow copy.
10. It is a good programming practice for the
equals
and
compareTo
methods to work
in noncontradictory fashion. In other words,
o1.equals(o2)
should be true exactly
when
o1.compareTo(o2)==0
.
11. We cannot assign weaker access privileges when overriding a method. For example, a
method that overrides a
public
method must be of type
public
.
12. All non-constant variables should be defined as
private
. Methods can be defined as
private
,nomodifier,
protected
,or
public
.
13. Polymorphism does not apply for
static
,
final
,or
private
methods.
8.17 Exercises
1. Can a subclass inherit the private members of the superclass as private members of
the subclass?
2. Consider the
Person
class.
class
Person
{
private
String name;
public
Person(String name)
{
this
.name=name;
}
}