1. Inheritance allows you to define a generic class (The parent Class), and then extend the class to a more specific class (subclass).
Subclasses inherit accessible data fields and methods from the parent class, and you can add new data fields and new methods.
Syntax: public class subclass extends superclass;
2. Private data fields in the parent class are inaccessible outside the class and cannot be used directly in the subclass, if the parent class
Public accessors/modifiers are defined so that they can be accessed in this way.
3.Java does not allow multiple inheritance, a Java class can inherit directly from a parent class (single inheritance Simple
inheritance), but multiple inheritance can be implemented through interfaces.
4.super keywords
1) Super refers to the parent class of the Super keyword.
2) Two types of applications:
I. Call the parent class's construction method;
Grammar: Super (); or super (parameters);
Must appear in the first row of the subclass construction method.
Construction method Chain:
If you do not explicitly call the overloaded constructor method or the constructor of the parent class, the compiler automatically
Super () as the first statement of the constructor method.
such as public ClassName () {
}
Equivalent to public ClassName () {
Super ();
}
(This process can be chained to the inheritance architecture after a constructor method is called)
II. Calling the method of the parent class;
Syntax: super.methodname (parameters);
Note: You generally do not need to add super because subclasses and methods that inherit the parent class. But when the method is rewritten
To call the parent class method, you must add super
Method overriding: You need to use the same signature as the parent class in the subclass
The return value type.
Use overriding annotations to avoid obfuscation of method overrides with method overloading errors:
Overriding a callout @override means that the method being labeled must override a method of the parent class that has the callout
method does not override the parent class's method, the compiler will report an error.
5. To design a class that can be inherited, it is best to provide a non-parametric construction method to avoid program errors.
public class Apple extends fruit{
}
Class fruit{
Public Fruit (String name)
{
}
}
Because there is no explicitly defined construction method in the subclass, the parameterless construction method is used by default, but is not defined in fruit
Without a parameter construction method, a compilation error occurs.
Beginner java--Classes and methods (2) Inheritance