The Help With Assignment Blog is intended to provide with tips and tricks to students so that they are able to do better at school and college. The Blog is associated with HelpWithAssignment.com (HwA), a leading provider of online tuitions in University subjects.

Friday, September 2, 2011

Java Subclassing and Inheritance With An Example

Java Subclassing and Inheritance

Classes in Java exist in hierarchy. A class in Java can be declared as a subclass of another class using the extends keyword. A subclass inherits variables and methods from its superclass and can use them as if they were declared within the subclass.

For example, if in a class,

class Animal {

float weight;

void eat() {

}

}

class Mammal extends Animal {

//inherits weight

int heartRate;

//inherits eat()

void breathe() {

}

}

In this example, an object of type Mammal has both the instance variable weight and the method eat(). They are inherited from Animal.

A class can extend only one other class. To use the proper terminology, Java allows single inheritance of class implementation. A subclass can be further subclassed. Normally, subclassing specializes or refines a class by adding variables and methods.

For example:

class Cat extends Mammal {

//inherits weight and inheritance

boolean longhair;

//inherits eat() and breathe()

void purr() {

}

}

The Cat class is a type of Mammal that is ultimately a type of Animal. Cat objects inherit all the characteristics of Mammal objects and in turn, Animal objects. Cat also provides additional behavior in the form of the purr() method and the long hair variable.

A subclass inherits all members of its superclass not designed as private. Other levels of visibility affect what inherited members of the class can be seen from outside of the class and its subclasses, but at a minimum, a subclass always has the same set of visible members as its parent. For this reason, a subclass always has the same set of visible members as its parent and instances of the subtype can be used anywhere instances of the supertype are allowed.

Another example,

Cat simon = new Cat ();

Animal creature = simon;

The Cat instance simon in the example can be assigned to the Animal type variable creature because Cat is a subtype of Animal. Similarly, any method accepting an Animal object would accept an instance of a cat or any Mammal type as well. This is an important aspect of polymorphism in an object-oriented language such as Java. This is used to refine a class’s behavior as well as add new capabilities to it.

For more details you can visit our websites at http://www.helpwithassignment.com/programing-assignment-help and http://www.helpwiththesis.com

No comments: