Java Inheritance
/*
This is a very similar topic to interfaces.
The key difference is that inheritance deals with two classes, not a class and an
interface.
Another key difference is that inheritance uses the keyword "extends" rather than
"implements."
So how is "extends" different from "implements?"
Recall that when you implement an interface, you must take all the abstract
qualities of the interface and implement it into the Class that is implementing it.
Not so when a class extends another class, which we refer to as a Superclass,
and the extending class is called a subclass.
A class is a blueprint for objects, as I have repeated over and over again.
A superclass is a blueprint for other classes.
In inheritance, we take an abstract concept, like Phone, and create a class which
will hold all the shared properties of all Phones. Then, we can use this as a
blueprint to create more specialized objects, such as the iPhone class or the GalaxyS class.
Let's have a look at an example:
*/
// This is the 'generic' superclass
class Phone {
// Phone class variables
int weight = 10;
int numProcessingCores = 4;
int price = 200;
boolean turnedOn = false;
public void togglePower() {
// turnedOn is now its opposite (true becomes false, and vice versa)
turnedOn = !turnedOn;
}
}
/*
This superclass holds all the information that all phones should have, such as
weight, number of cores, price and etc. Using this superclass, we can create a
subclass, which will (this is key) ADD ITS OWN UNIQUE PROPERTIES to the GENERIC
properties described in the superclass (meaning that iPhone below will have all
the methods and variables in the Phone method and also its own methods and variables):
*/
public class iPhone extends Phone {
boolean hasAppleLogo = true;
String color = "black";
void adjustPrice() {
if (hasAppleLogo) {
// Although we did not declare a price variable in this class
// we have inherited a copy of it from the Phone class.
price += 4500;
}
}
}
//Now the class iPhone will be able to use all the methods and constants defined
//in the superclass Phone... and add its own methods (like adjustPrice())
//Now the class iPhone will be able to use all the methods and variables defined
//in the superclass Phone... and add its own methods (like adjustPrice())
Inheritance in Java
Herencia en Java