GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||
GeezerVison is showing jenkov.com — Java Inheritance Java Language
Java Inheritance
Java inheritance refers to the ability in Java for one class to inherit from another class. In Java this is also called extending a class. One class can extend another class and thereby inherit from that class. When one class inherits from another class in Java, the two classes take on certain roles. The class that extends (inherits from another class) is the subclass and the class that is being extended (the class being inherited from) is the superclass . In other words, the subclass extends the superclass. Or, the subclass inherits from the superclass. Another commonly used term for inheritance is specialization and generalization. A subclass is a specialization of a superclass, and a superclass is a generalization of one or more subclasses. Inheritance is a Method of Code ReuseInheritance can be an effective method to share code between classes that have some traits in common, yet allowing the classes to have some parts that are different.
Here is diagram illustrating a class called
The
Note: Some people will claim that inheritance is a way to categorize your classes based on what they are.
A
For instance, do you need to refer to Class HierarchiesSuperclasses and subclasses form an inheritance structure which is also called a class hierarchy. At the top of the class hierarchy you have the superclasses. At the bottom of the class hierarchy you have the subclasses. A class hierarchy may have multiple levels, meaning multiple levels of superclasses and subclasses. A subclass may itself be a superclass of other subclasses etc. Java Inheritance BasicsWhen a class inherits from a superclass, it inherits parts of the superclass methods and fields. The subclass can also override (redefine) the inherited methods. Fields cannot be overridden, but can be "shadowed" in subclasses. How all this works is covered later in this text. What is Inherited?
When a subclass extends a superclass in Java, all
Fields and methods with default (package) access modifiers can be accessed by subclasses only if the subclass is located
in the same package as the superclass. Private fields and methods of the superclass can never be referenced
directly by subclasses. They can, however, be referenced indirectly via methods reachable from the subclass
(e.g default (package), Constructors are not inherited by subclasses, but a subclass constructor must call a constructor in the superclass. This will be explained in detail in a later section. Java Only Supports Singular InheritanceThe Java inheritance mechanism only allows a Java class to inherit from a single superclass (singular inheritance). In some programming languages, like C++, it is possible for a subclass to inherit from multiple superclasses (multiple inheritance). Since multiple inheritance can create some weird problems, if e.g. the superclasses contain methods with the same names and parameters, multiple inheritance was left out in Java. Declaring Inheritance in Java
In Java inheritance is declared using the public class Vehicle {
protected String licensePlate = null;
public void setLicensePlate(String license) {
this.licensePlate = license;
}
}
public class Car extends Vehicle {
int numberOfSeats = 0;
public String getNumberOfSeats() {
return this.numberOfSeats;
}
}
The
Because the
The public class Car extends Vehicle {
int numberOfSeats = 0;
public String getNumberOfSeats() {
return this.numberOfSeats;
}
public String getLicensePlate() {
return this.licensePlate;
}
}
The referencing happens inside the
In many cases it would have made sense to place the Inheritance and Type Casting
It is possible to reference a subclass as an instance of one of its superclasses. For instance, using the class definitions from
the example in the previous section it is possible to reference an instance of the
Here is a Java code example: Car car = new Car(); Vehicle vehicle = car;
First a
As you can see, it is possible to use an instance of some subclass as if it were an instance of
its superclass. That way, you don't need to know exactly what subclass the object is an
instance of. You could treat e.g. both The process of referencing an object of class as a different type than the class itself is called type casting. You cast an object from one type to another. Upcasting and DowncastingYou can always cast an object of a subclass to one of its superclasses. This is referred to as upcasting (from a subclass type to a superclass type). It may also be possible to cast an object from a superclass type to a subclass type, but only if the object really is an instance of that subclass (or an instance of a subclass of that subclass). This is referred to as downcasting (from a superclass type to a subclass type). Thus, this example of downcasting is valid: Car car = new Car(); // upcast to Vehicle Vehicle vehicle = car; // downcast to car again Car car2 = (Car) vehicle;
However, the following downcast example is not valid. The Java compiler will accept it, but at runtime when this
code is executed the code will throw a Truck truck = new Truck(); // upcast to Vehicle Vehicle vehicle = truck; // downcast to car again Car car = (Car) vehicle;
The Overriding MethodsIn a subclass you can override (redefine) methods defined in the superclass. Here is a Java method override example: public class Vehicle {
String licensePlate = null;
public void setLicensePlate(String licensePlate) {
this.licensePlate = licensePlate;
}
}
public class Car extends Vehicle {
public void setLicensePlate(String license) {
this.licensePlate = license.toLowerCase();
}
}
Notice how both the To override a method the method signature in the subclass must be the same as in the superclass. That means that the method definition in the subclass must have exactly the same name and the same number and type of parameters, and the parameters must be listed in the exact same sequence as in the superclass. Otherwise the method in the subclass will be considered a separate method. In Java you cannot override private methods from a superclass. If the superclass calls a private method internally from some other method, it will continue to call that method from the superclass, even if you create a private method in the subclass with the same signature. The @override AnnotationIf you override a method in a subclass, and the method is all of a sudden removed or renamed or have its signature changed in the superclass, the method in the subclass no longer overrides the method in the superclass. But how do you know? It would be nice if the compiler could tell you that the method being overridden no longer overrides a method in the superclass, right?
This is what the Java public class Car extends Vehicle {
@Override
public void setLicensePlate(String license) {
this.licensePlate = license.toLowerCase();
}
}
Calling Superclass Methods
If you override a method in a subclass, but still need to call the method defined in the superclass,
you can do so using the public class Car extends Vehicle {
public void setLicensePlate(String license) {
super.setLicensePlate(license);
}
}
In the above code example the method
You can call superclass implementations from any method in a subclass, like above. It does not have
to be from the overridden method itself. For instance, you could also have called The instanceof Instruction
Java contains an instruction named Car car = new Car(); boolean isCar = car instanceof Car;
After this code has been executed the
The Car car = new Car(); boolean isVehicle = car instanceof Vehicle;
Assuming that the
As you can see, the
The variable type used with the Car car = new Car(); Vehicle vehicle = car; boolean isCar = vehicle instanceof Car;
Even though the
Here is the same Truck truck = new Truck(); Vehicle vehicle = truck; boolean isCar = vehicle instanceof Car;
After executing this code the Fields and InheritanceAs mentioned earlier, in Java fields cannot be overridden in a subclass. If you define a field in a subclass with the same name as a field in the superclass, the field in the subclass will hide (shadow) the field in the superclass. If the subclass tries to access the field, it will access the field in the subclass. If, however, the subclass calls up into a method in the superclass, and that method accesses the field with the same name as in the subclass, it is the field in the superclass that is accessed. Here is Java inheritance example that illustrates how fields in subclasses shadow (hides) fields in superclasses: public class Vehicle {
String licensePlate = null;
public void setLicensePlate(String licensePlate) {
this.licensePlate = licensePlate;
}
public String getLicensePlate() {
return licensePlate;
}
}
public class Car extends Vehicle {
protected String licensePlate = null;
@Override
public void setLicensePlate(String license) {
super.setLicensePlate(license);
}
@Override
public String getLicensePlate() {
return super.getLicensePlate();
}
public void updateLicensePlate(String license){
this.licensePlate = license;
}
}
Notice how both classes have a
Both the
The Look at the following lines of Java code: Car car = new Car();
car.setLicensePlate("123");
car.updateLicensePlate("abc");
System.out.println("license plate: "
+ car.getLicensePlate());
This Java code will print out the text
The Constructors and Inheritance
The Java inheritance mechanism does not include constructors. In other words, constructors of a superclass are not
inherited by subclasses. Subclasses can still call the constructors in the superclass using the public class Vehicle {
public Vehicle() {
}
}
public class Car extends Vehicle{
public Car() {
super();
//perform other initialization here
}
}
Notice the call to You may have seen Java classes where the subclass constructors did not seem to call the constructors in the superclass. Maybe the superclass did not even have a constructor. However, the subclass constructors have still called superclass constructors in those case. You just could not see it. Let me explain why:
If a class does not have any explicit constructor defined, the Java compiler inserts an implicit no-arg constructor.
Thus, a class always has a constructor. Therefore the following version of public class Vehicle {
}
Second, if a constructor does not explicitly call a constructor in the superclass, the Java compiler inserts an
implicit call to the no-arg constructor in the superclass. That means that the following version of the public class Car extends Vehicle{
public Car() {
}
}
In fact, since the constructor is now empty, we could leave it out and the Java compiler would insert it, and insert an implicit call to the no-arg constructor in the superclass. This is how the two classes would look then: public class Vehicle {
}
public class Car extends Vehicle{
}
Even though no constructors are declared in these two classes, they both get a no-arg constructor, and the no-arg
constructor in the
If the Nested Classes and Inheritance
The same Java inheritance rules apply to nested classes. Nested classes which
are declared Here is a nested class inheritance example: class MyClass {
class MyNestedClass {
}
}
public class MySubclass extends MyClass {
public static void main(String[] args) {
MySubclass subclass = new MySubclass();
MyNestedClass nested = subclass.new MyNestedClass();
}
}
Notice how it is possible to create an instance of the nested class Final Classes and Inheritance
A class can be declared public final class MyClass {
}
A Abstract Classes and Inheritance
In Java a class can be declared
An
In Java Next: Java Nested Classes
Close TOC
All Trails Trail TOC Page TOC Previous Next | ||||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. | ||||||||