Java Subclassing and Inheritance from Help With Assignment
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 https://www.helpwithassignment.com/programing-assignment-help
Book Your Assignment
Recent Posts
How To Prepare An Excellent Thesis Defense?
Read MoreHow to Restate A Thesis? – A Detailed Guide
Read MoreExplanatory Thesis: Examples and Guide for Clear Writing
Read MoreHow To Write 3 Types Of Thesis Statements?
Read MoreHow to Effectively Prepare for Your Thesis Defense?
Read MoreGet assignment help from subject matter experts!
4.7/5 rating | 10,000+ happy students | Great tutors 24/7