Docsity

Java: Understanding Method Overriding, Overloading, and the Object Class, Slides of Java Programming

Partial preview of the text

Download Java: Understanding Method Overriding, Overloading, and the Object Class and more Slides Java Programming in PDF only on Docsity!

OUTPUT

๏‚— The output from this program is shown here:

๏‚— Contents of superOb:

๏‚— i and j: 10 20

๏‚— Contents of subOb:

๏‚— i and j: 7 8

๏‚— k: 9

๏‚— Sum of i, j and k in subOb:

๏‚— i+j+k: 24

Example

public class Animal { public Animal(String aType) { type = new String(aType); } public String toString() { return โ€œThis is a โ€œ + type; } private String type; }

Constructors of the Derived Class

public class Dog extends Animal { public Dog(String aName) { super(โ€œDogโ€); name = aName; breed = โ€œUnknownโ€; } public Dog(String aName, String aBreed) { super(โ€œDogโ€); name = aName; breed = aBreed; } private String name; private String breed; }

Overriding a Base Class Method

public String toString() {

return โ€œItโ€™s โ€œ + name + โ€œ the โ€œ + breed;

Another use of Super

public String toString() {

return super.toString() + โ€œ\nItโ€™s โ€œ + name + โ€œ the โ€œ + breed;

Overloading vs. Overriding

23 ๏‚— Overloading deals with multiple methods in the same class with the same name but different signatures ๏‚— Overloading lets you define a similar operation in different ways for different data ๏‚— Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature ๏‚— Overriding lets you define a similar operation in different ways for different object types

๏‚— Use protected when you want a limited access to the

subclasses in other packages

The Object Class

26 ๏‚— A class called Object is defined in the java.lang package of the Java standard class library ๏‚— All classes are derived from the Object class ๏‚— even if a class is not explicitly defined to be the child of an existing class, it is assumed to be the child of the Object class ๏‚— the Object class is therefore the ultimate root of all class hierarchies ๏‚— The Object class contains a few useful methods, which are inherited by all classes ๏‚— toString() ๏‚— equals() ๏‚— clone()

The Object Class: the equals Method

๏‚— The equals method of the Object class determines

if two variables point to the same object (more

shortly)

๏‚— Many classes (which all implicitly extend an

Object class) override equals to define equality in

some other way, e.g. Integer.equals looks at the

represented integer, etc.

EXAMPLE class Animal { private String type; public Animal(String aType) { type = new String(aType); } public void eat() { System.out.println("Animal eat"); } }