Inherited Methods and Overriding



Inherited Methods and Overriding

In Java, all non-primitives follow an inheritance structure. We will cover this in more detail when we specifically talk about inheritance, but we'll cover the idea of "overriding" a method here.

All classes in Java inherit from the Object class. Thus, all non-primitives ARE Object objects, so to speak. In this class, a toString() method is defined. Thus, if you write your own class, but don't define a toString() method, then when you try to print out your object, technically, the toString() method from the Object class gets called.

Consider the fraction class. Let us omit its toString() method, compile and rerun the code. Instead of our fractions printing like 2/3, we'll get something to the effect of fraction@10b62c9. The former represents the output of the toString() method defined in the fraction class, and the latter represents the output of the toString() method in the Object class.

Whenever one class (class B) inherits from another class (class A) in Java, if we omit a definition of a method in class B and one exists in class A, then the method in class A will be executed on an object of type class B.

In some instances, this is desirable. In others, like the example above, it makes sense for us to "override" the toString() method in the Object class when we create the fraction class, since no one would understand what fraction@10b62c9 really means!

clone() method

Often times, it makes sense to produce a duplicate of an object instead of having two references to the same object.

For example, the lines of code:

fraction f = new fraction(1,2);

fraction copy = f;

Actually produces the following picture:

f ---------------> [ num = 1, den = 2] ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download