Java Reference
In-Depth Information
The default toString() method, although sometimes useful, is not very excit-
ing. Instead of using the default version, the Radio class can include its own
toString() method, allowing the Radio class to create its own string representa-
tion of a Radio object. Adding toString() to the Radio class replaces the
toString() method in Object. This is an example of method overriding, which
we will now discuss.
Method Overriding
A child class can override a method that it inherits from a parent, thereby
allowing the child class to add or change the behavior of the method in the
parent. This is referred to as method overriding and is a feature of OOP.
Here is a list of rules that must be followed when a child class overrides a
method in a parent class:
The return type, method name, and parameter list must be identical.
■■
The access specifier must be at least that of the parent. For example,
if the parent method is public, the child must be public. If the parent
method is protected, the child must be protected or public (public
allows more access than protected).
■■
The overriding exception cannot throw more exceptions than the parent.
(The reason for this is discussed in Chapter 11, “Exception Handling.”)
■■
If a method in the child class has the same name as a method in the
parent class, but the child class method changes the parameter list, then
this is method overloading, not method overriding. Try not to confuse the
two concepts, since their usages are quite different.
The Radio class discussed earlier inherited all the methods of Object but did
not override any of them. The following Radio in class overrides the toString()
method, thereby replacing the toString() behavior of toString() in Object.
public class Radio
{
public int volume;
public double channel;
public char band;
public Radio(int v, double c, char b)
{
volume = v;
channel = c;
band = b;
}
Search WWH ::




Custom Search