https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
Definitions: A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass(also a base class or a parent class).
Excepting
Object
, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object
.Classes can be derived from classes that are derived from classes that are derived from classes, and so on, and ultimately derived from the topmost class,
Object
. Such a class is said to be descended from all the classes in the inheritance chain stretching back to Object
.Why inheritance?
The idea of inheritance is simple but powerful: When you want to create a new class and there is already a class that includes some of the code that you want, you can derive your new class from the existing class. In doing this, you can reuse the fields and methods of the existing class without having to write (and debug!) them yourself.
A subclass inherits all the members (fields, methods, and nested classes) from its superclass.
Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.
Object
is the most general of all classesWhat You Can Do in a Subclass
A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-privatemembers of the parent. You can use the inherited members as is, replace them, hide them, or supplement them with new members:
- The inherited fields can be used directly, just like any other fields.
- You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it (not recommended).
- You can declare new fields in the subclass that are not in the superclass.
- The inherited methods can be used directly as they are.
- You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it.
- You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it.
- You can declare new methods in the subclass that are not in the superclass.
- You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword
super
.
Private Members in a Superclass
A subclass does not inherit the
private
members of its parent class.
However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.
A nested class has access to all the private members of its enclosing class—both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass.
Casting Objects (https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html)
This cast inserts a runtime check that
obj
is assigned a MountainBike
so that the compiler can safely assume that obj
is a MountainBike
. If obj
is not a MountainBike
at runtime, an exception will be thrown.Note: You can make a logical test as to the type of a particular object using the
instanceof
operator. This can save you from a runtime error owing to an improper cast. For example:if (obj instanceof MountainBike) { MountainBike myBike = (MountainBike)obj; }
instanceof
operator verifies that obj
refers to a MountainBike
so that we can make the cast with knowledge that there will be no runtime exception thrown.Multiple Inheritance of State, Implementation, and Type
One significant difference between classes and interfaces is that classes can have fields whereas interfaces cannot.
The Java programming language supports multiple inheritance of type, which is the ability of a class to implement more than one interface. An object can have multiple types: the type of its own class and the types of all the interfaces that the class implements. This means that if a variable is declared to be the type of an interface, then its value can reference any object that is instantiated from any class that implements the interface
Overriding and Hiding Methods
Instance Methods
The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method that it overrides. An overriding method can also return a subtype of the type returned by the overridden method. This subtype is called a covariant return type.
When overriding a method, you might want to use the
@Override
annotation that instructs the compiler that you intend to override a method in the superclass.
Note:
@override is not required for subclass methods to override superclass methods.
@override is not required for subclass methods to override superclass methods.
Static Methods
If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass.
The distinction between hiding a static method and overriding an instance method has important implications:
- The version of the overridden instance method that gets invoked is the one in the subclass.
- The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass.
Summary
The following table summarizes what happens when you define a method with the same signature as a method in a superclass.
Superclass Instance Method | Superclass Static Method | |
---|---|---|
Subclass Instance Method | Overrides | Generates a compile-time error |
Subclass Static Method | Generates a compile-time error | Hides |
Note: In a subclass, you can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass instance methods—they are new methods, unique to the subclass.
Polymorphism
Hiding Fields
Within a class, a field that has the same name as a field in the superclass hides the superclass's field, even if their types are different. Within the subclass, the field in the superclass cannot be referenced by its simple name. Instead, the field must be accessed through
super
, which is covered in the next section. Generally speaking, we don't recommend hiding fields as it makes code difficult to read.class A {
public Horse getAnimal (){
return new Horse();
}
}
class B extends A {
public Pegasus getAnimal (){
super.getAnimal();
return new Pegasus();
}
}
class Pegasus extends Horse implements Flyer, Mythical {
public String identifyMyself() {
return "I am a pegasus";
}
}
class Horse {
public String identifyMyself() {
return "I am a horse.";
}
}
interface Flyer {
default public String identifyMyself() {
return "I am able to fly.";
}
}
interface Mythical {
default public String identifyMyself() {
return "I am a mythical creature.";
}
}
class Company {
public void address() {
System.out.println("This is Address of Crunchify Company...");
}
}
class eBay extends Company {
@Override
public void address() {
super.address();
System.out.println("This is eBay's Address...");
}
}
public class Test {
public static void main(String args[]) {
Company a = new Company(); // Company reference and object
Company b = new eBay(); // Company reference but eBay object
a.address();// runs the method in Company class
b.address();// Runs the method in eBay class
Pegasus myApp = new Pegasus();
System.out.println(myApp.identifyMyself());
A a1 = new A();
B b1 = new B();
String sa = a1.getAnimal().identifyMyself();
String sb = b1.getAnimal().identifyMyself();
System.out.println("sa = " + sa);
System.out.println("sb = " + sb);
}
}
// output:
This is Address of Crunchify Company...
This is Address of Crunchify Company...
This is eBay's Address...
I am a pegasus
sa = I am a horse.
sb = I am a pegasus
Using the Keyword super
Accessing Superclass Members
Subclass Constructors
Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error.
Object
does have such a constructor, so if Object
is the only superclass, there is no problem.If a subclass constructor invokes a constructor of its superclass, either explicitly or implicitly, you might think that there will be a whole chain of constructors called, all the way back to the constructor of
Object
. In fact, this is the case. It is called constructor chaining, and you need to be aware of it when there is a long line of class descent.Summary
- Except for the
Object
class, a class has exactly one direct superclass. A class inherits fields and methods from all its superclasses, whether direct or indirect. A subclass can override methods that it inherits, or it can hide fields or methods that it inherits. (Note that hiding fields is generally bad programming practice.) - The table in Overriding and Hiding Methods section shows the effect of declaring a method with the same signature as a method in the superclass.
- The
Object
class is the top of the class hierarchy. All classes are descendants from this class and inherit methods from it. Useful methods inherited fromObject
includetoString()
,equals()
,clone()
, andgetClass()
. - You can prevent a class from being subclassed by using the
final
keyword in the class's declaration. Similarly, you can prevent a method from being overridden by subclasses by declaring it as a final method. - An abstract class can only be subclassed; it cannot be instantiated. An abstract class can contain abstract methods—methods that are declared but not implemented. Subclasses then provide the implementations for the abstract methods.
Quiz
Question 1: Consider the following two classes:
public class ClassA { public void methodOne(int i) { } public void methodTwo(int i) { } public static void methodThree(int i) { } public static void methodFour(int i) { } } public class ClassB extends ClassA { public static void methodOne(int i) { } public void methodTwo(int i) { } public void methodThree(int i) { } public static void methodFour(int i) { } }
Question 1a: Which method overrides a method in the superclass?
Answer 1a:
Answer 1a:
methodTwo
Question 1b: Which method hides a method in the superclass?
Answer 1b:
Answer 1b:
methodFour
Question 1c: What do the other methods do?
Answer 1c: They cause compile-time errors.
Answer 1c: They cause compile-time errors.
No comments:
Post a Comment