Table of Contents
- What is inheritance?
- What are the benefits of inheritance?
- Characteristics of inheritance
- Notes on using inheritance
- What is the difference between super and this?
- Method overriding (overwriting)
- The final keyword
- Polymorphism
- Abstraction (abstract)
- Inner classes
- Content modified by different modifiers (unrelated to inner classes)
- Four access modifiers
What is inheritance?
When multiple classes have the same attributes and behaviors, extract these contents into a single class. Then the multiple classes no longer need to define these attributes and behaviors; they only need to inherit that class.
The multiple classes can be calledsubclasses, and this single class is called theparent class、superclassorbase class。
Subclasses can directly access thenon-privateattributes and behaviors in the parent class.
Through theextendskeyword, an inheritance relationship is created between classes.
class SubDemo extends Demo{} //SubDemo是子类,Demo是父类
What are the benefits of inheritance?
- Improvescode reusability。
- Creates relationships between classes, which is theprerequisite for polymorphism.。
Characteristics of inheritance
1. Java only supports single inheritance, not multiple inheritance.
//一个类只能有一个父类,不可以有多个父类。
class SubDemo extends Demo{} //ok
class SubDemo extends Demo1,Demo2...//error
2. Java supports multi-level (repeated) inheritance (inheritance hierarchy).
class A{}
class B extends A{}
class C extends B{}
Notes on using inheritance
- If there is an "is a" relationship between classes, consider using inheritance.
- Do not use inheritance just to inherit part of the functionality.
What is the difference between super and this?
supersuper is a keyword that represents the parent class'sstorage space identifier. (It can be understood as a reference to the parent.)
The usage of super and this is similar.
this representsa reference to the object(whoever calls it, it represents that object);
super representsthe current subclass'sPairparent classreference.
Usage scenarios
- When the child and parent classes have members with the same name, super can be used to distinguish them;
- When a subclass needs to call the parent class constructor, the super statement can be used.
Differences
1. Member variables
this.变量 -- 本类的 super.变量 -- 父类的
2. Constructors
this(...) -- 本类的 super(...) -- 父类的
3. Member methods
this.方法名() -- 本类的 super.方法名() -- 父类的
super(); and this(); must both be on the first line of the constructor, and they cannot appear at the same time.
Method overriding (overwriting)
When a subclass has a method exactly the same as the parent class method (except the access modifier, the access modifier must be greater than or equal and not private; return type, method name, and parameter list are the same), an overriding operation occurs, also called rewriting or overwriting.
Private methods of the parent class are invisible to the subclass, so overriding private methods of the parent class is out of the question.
Notes on overriding:
- When overriding, the access level of the subclass method must be greater than or equal to that of the parent class method;
- Static methods can only override static methods.
Use cases for overriding:
When the subclass needs the functionality of the parent class, but the function body has content specific to the subclass, the method in the parent class can be overridden. In this way, it not only inherits the parent class's functionality but also defines content specific to the subclass.
What is the difference between method overriding and overloading??
Method overriding is used when the subclass method is exactly the same as the parent class method; except for the access modifier, the return type, method name, and parameter list are all the same.
Overloading is used when methods in the same class have the same method name but different parameter lists (it has nothing to do with the return type).
Usage of constructors in child and parent classes:
- During the initialization of a subclass, the initialization of the parent class is executed first. This is because the subclass constructor has a default super() call. The subclass needs to use the member variables of the parent class, and this initialization must be completed before the subclass initialization. Therefore, during subclass initialization, the parent class initialization is executed first.
- If the parent class has no no-argument constructor
- Use super to call the parent class's parameterized constructor. Recommended approach.
- Use this to call other constructors of the same class.
Execution order of static code blocks, constructor code blocks, and constructors:
Parent class static code block → subclass static code block → parent class constructor code block → parent class constructor → subclass constructor code block → subclass constructor
The final keyword
final is a keyword that can be used to modify classes, member variables, and member methods.
Characteristics:
- The class it modifies cannot be inherited.
- The member variable it modifies is a constant.
- The member method it modifies cannot be overridden by subclasses.
Constants modified by final generally have naming conventions. For constants modified by final, all letters areuppercase.。
A member variable modified by final must be initialized. There are two ways to initialize it:
- Explicit initialization;
- Constructor initialization.
But the two cannot be used together for initialization.
The difference between final and private:
- A class modified by final can be accessed;
private cannot modify outer classes, but it can modify inner classes (in fact, making an outer class private is meaningless). - Methods modified by final cannot be overridden by subclasses;
Methods modified by private appear to be overridable by subclasses, but in fact they cannot be, because subclasses cannot see the private methods of the parent class. - A variable modified by final can only be assigned once during explicit initialization or constructor initialization, and cannot be changed afterward;
A variable modified by private is also not allowed to be directly accessed or modified by subclasses or other classes in the same package, but it can be modified and retrieved through set and get methods.
Polymorphism
Concept:
The different states that an object exhibits at different times.
Prerequisites for polymorphism:
- There must be an inheritance or implementation relationship.
- There must be method overriding.
- There must be a parent class reference pointing to a subclass object.
Manifestation in programs:
A reference of the parent class or interface points to or receives its ownsubclass object.。
Benefits and effects:
The existence of polymorphism improves the program'sextensibilityand latermaintainability.。
Disadvantages:
When a parent class is called, only methods in the parent class can be called, not the subclass's specific methods, because you do not know what kind of subclasses will inherit it in the future.
Member characteristics of polymorphism:
- Member variables: At compile time: check whether the class to which the reference variable belongs has the variable being called;
At runtime: also check whether the class to which the reference variable belongs has the variable being called.
For member variables, both compile time and runtime depend on the class to which the reference variable belongs. Simply remember:For member variables, both compilation and runtime look at the left side of the equals sign.。 - Member methods: At compile time: check whether the class to which the reference variable belongs has the member being called;
At runtime: check whether the class to which the object belongs has the member being called. If the parent and child have methods with the same name, the subclass method will run, because methods have the overriding characteristic.
Compilation looks at the left, runtime looks at the right.。 - Static methods: At compile time: check whether the class to which the reference variable belongs has the variable being called;
At runtime: also check whether the class to which the reference variable belongs has the variable being called.
Both compilation and runtime look at the left side of the equals sign.。
You absolutely must not convert a parent class object to a subclass type!
A parent class reference pointing to a subclass object can be upcast, and can also beforced/cast.。
Throughout polymorphism, it is always the subclass object that is changing!
//多态向下转型和向上转型的例子,多态转型解决了多态中父类引用不能使用子类特有成员的弊端。
class PolymorphicTest2 {
public static void main(String[] args) {
Phone p1 = new Nokia(); //向上转型,类型提升
Nokia no = (Nokia)p1; //向下转型,强制将父类的引用转换成子类类型,不能将Nokia类型转成Moto或Nexus类型
no.print(); //输出结果为Phone---null---0,因为继承了父类的方法
Phone p2 = new Moto();
Moto m = (Moto)p2;
m.print(); //输出结果为Moto---yellow---1599,方法重写,子类方法覆盖父类方法
Phone p3 = new Nexus();
Nexus ne = (Nexus)p3;
ne.print();
}
}
class Phone{
String color;
int price;
public void print(){
System.out.println("Phone---" + color + "---" + price );
}
}
class Nokia extends Phone{
String color = "red";
int price = 1009;
//public void print(){
// System.out.println("Nokia---" + color + "---" + price);
//}
}
class Moto extends Phone{
String color = "yellow";
int price = 1599;
public void print(){
System.out.println("Moto---" + color + "---" + price);
}
}
class Nexus extends Phone{
String color = "black";
int price = 1999;
public void print(){
System.out.println("Nexus---" + color + "---" + price);
}
}
}
Abstraction (abstract)
Abstraction is extracting common and essential content from multiple things.
Abstract classes:
In Java, you can definemethods without a method body.The specific implementation of such a method is provided bySubclassAn incomplete method is called an abstract method, and a class containing an abstract method is an abstract class.
Origin:
When multiple objects all have the same function, but the specific content of the function differs, during the extraction process only the function definition is extracted, not the function body. A method that has only a function declaration and no function body is called an abstract method.
Characteristics of abstract classes:
- Abstract methods must be in an abstract class;
- Both abstract methods and abstract classes must be modified with the `abstract` keyword;
- Abstract classes cannot use `new` to create objects, because calling an abstract method is meaningless;
- For the abstract methods in an abstract class to be used, a subclass must override all its abstract methods and then create a subclass object to call them; if a subclass only overrides part of the abstract methods, it is still an abstract class;
- An abstract class can have abstract methods or non-abstract methods; abstract methods are used for subclass instantiation;
- If a class is an abstract class, then the subclasses that inherit it must either be abstract classes or override all abstract methods.
Special case: an abstract class may not define abstract methods; this is only to prevent the class from creating objects.
Member characteristics of abstract classes:
- Member variables: can be variables or constants;
- Constructors: there are constructors;
- Member methods: can be abstract methods or non-abstract methods.
abstract class 葵花宝典 {
public abstract void 自宫();
}
class 岳不群 extends 葵花宝典 {
public void 自宫(){
System.out.println("剪刀");
}
}
class 林平之 extends 葵花宝典{
public void 自宫(){
System.out.println("指甲刀");
}
}
class AbstractTest {
public static void main(String[] args) {
岳不群 岳 = new 岳不群();
岳.自宫();
林平之 林 = new 林平之();
林.自宫();
}
}
Precautions for abstract classes:
An abstract class cannot be instantiated; why does it still have a constructor??
As long as a class is defined with `class`, it must have a constructor. The constructor in an abstract class is used to instantiate subclasses.
A class has no abstract methods; why is it defined as an abstract class??
It wants to be inherited, but not to be instantiated.
Which keywords cannot coexist with the abstract keyword `abstract`??
- `final`: if a method is abstract, it needs to be overridden, but `final` cannot be overridden, so they conflict.
- `private`: if a method is private, subclasses cannot directly access it, so how can it be overridden?
- `static`: no object is needed, and the abstract method can be called by the class name. But calling an abstract method is meaningless.
Interface (`interface`)
InterfaceYesAbstract methodsandConstant valuesA collection of. Essentially, an interface is a special kind of abstract class that contains only constants and method definitions, without variables and method implementations.
Format:`interface InterfaceName {}`
The emergence of interfaces expresses "multiple inheritance" in another form, namely "multiple implementation".
Implementation (`implements`)
Format:`class ClassName implements InterfaceName {}`
Characteristics:
- Interfaces cannot be instantiated.
- If a class implements an interface, it must either be an abstract class or implement all the methods in the interface.
Member characteristics of interfaces:
The member modifiers in an interface are fixed!
- Member constants: `public static final`. Variables defined in an interface are global constants, and the modifiers can only be these three keywords; all of them can be omitted. Constant names must be uppercase.
- Member methods: `public abstract`. Methods defined in an interface are all abstract, and the two modifier keywords can be omitted.
- Recommendation: always provide the modifiers manually.
Differences between inheritance and implementation:
- The relationship between classes and classes is called inheritance: because whether a class is abstract or non-abstract, it can define non-abstract methods inside, and these methods can be used directly by subclasses; subclasses only need to inherit. Only single inheritance is allowed, and multi-level inheritance is allowed.(class))
- The relationship between a class and an interface is implementation: because all methods in an interface are abstract, they must be implemented by a subclass before it can be instantiated. A class can have a single implementation or multiple implementations; it can also implement multiple interfaces while inheriting a class.(class) extends (class) implements (interface1,interface2…))
- The relationship between interfaces and interfaces is inheritance: one interface can inherit another interface and add new properties and abstract methods, and interfaces can have multiple inheritance.(interface) extends (interface1,interface2…))
Differences between abstract classes and interfaces:
Member variables
- An abstract class can have variables and constants
- An interface can only have constants
Member methods
- An abstract class can have non-abstract methods and abstract methods
- An interface can only have abstract methods
Constructors
- Abstract classes have constructors
- Interfaces do not have constructors
Relationship among classes, abstract classes, and interfaces
- The relationship between a class and an abstract class is inheritance `extends`
- The relationship between a class and an interface is implementation `implements`
Conceptual characteristics of interfaces:
- An interface isexternally exposedrules;
- An interface is thefunctional extension;
- of a program;The emergence of interfacesreduces coupling; (it implements modular development: rules are defined, everyone implements their own module, greatly improving development efficiency)
- Interfaces can be used formultiple implementation;
- Multipleunrelated classes can implement the same interface;
- A class can implementmultipleinterfaces that have no direct relationship with each other;
- Similar to the inheritance relationship, between an interface and its implementation class there existspolymorphism。
//运动员和教练的案例(下图是思路分析)
/*
篮球运动员和教练
乒乓球运动员和教练
现在篮球运动员和教练要出国访问,需要学习英语
请根据你所学的知识,分析出来哪些是类,哪些是抽象类,哪些是接口
*/
interface SpeakEnglish {
public abstract void speak();
}
interface GoAboard{
public abstract void aboard();
}
abstract class Person {
private String name;
private int age;
public Person(){}
public Person(String name,int age){
this.name = name;
this.age = age;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
//吃饭
public abstract void eat();
//睡觉
public void sleep(){
System.out.println("Zzz...");
}
}
//运动员
abstract class Player extends Person {
public abstract void study();
}
//教练
abstract class Coach extends Person {
public abstract void teach();
}
//篮球运动员
class BasketballPlayer extends Player implements SpeakEnglish,GoAboard{
public void eat(){
System.out.println(getAge() + "岁的" + getName() + "吃鸡腿");
}
public void study(){
System.out.println(getAge() + "岁的" + getName() + "学扣篮");
}
public void speak(){
System.out.println(getAge() + "岁的" + getName() + " Say Hello World");
}
public void aboard(){
System.out.println(getAge() + "岁的" + getName() + " Go Aboard");
}
}
//乒乓运动员
class PingPangPlayer extends Player{
public void eat(){
System.out.println(getAge() + "岁的" + getName() + "吃鸡蛋");
}
public void study(){
System.out.println(getAge() + "岁的" + getName() + "学扣球");
}
}
//篮球教练
class BasketballCoach extends Coach implements SpeakEnglish {
public void eat(){
System.out.println(getAge() + "岁的" + getName() + "啃鸡爪");
}
public void teach(){
System.out.println(getAge() + "岁的" + getName() + "教扣篮");
}
public void speak(){
System.out.println(getAge() + "岁的" + getName() + " Say Hello Java");
}
public void aboard(){
System.out.println(getAge() + "岁的" + getName() + " Go Aboard");
}
}
//乒乓球教练
class PingPangCoach extends Coach{
public void eat(){
System.out.println(getAge() + "岁的" + getName() + "吃鸡蛋皮");
}
public void teach(){
System.out.println(getAge() + "岁的" + getName() + "教扣球");
}
}
class PlayerAndCoach {
public static void main(String[] args) {
//篮球运动员
BasketballPlayer bp = new BasketballPlayer();
bp.setName("郭艾伦");
bp.setAge(33);
bp.eat();
bp.sleep();
bp.study();
bp.speak();
bp.aboard();
System.out.println("***********************");
//篮球教练
BasketballCoach bc = new BasketballCoach();
bc.setName("波波维奇");
bc.setAge(65);
bc.eat();
bc.sleep();
bc.teach();
bc.speak();
bc.aboard();
System.out.println("***********************");
//多态
Person p = new BasketballPlayer();
p.setName("Kobe Bryant");
p.setAge(33);
p.eat();
p.sleep();
//p.study();
//p.speak();
BasketballPlayer bp2 = (BasketballPlayer)p;
bp2.study();
bp2.speak();
bp2.aboard();
System.out.println("***********************");
}
}
Inner classes
Defining a class inside another class; the inner class is called an inner class. The emergence of inner classes once again breaks the limitation of Java's single inheritance.
Access characteristics:
- An inner class can directly access members of the outer class, including private members.
- For the outer class to access members of the inner class, it must create an object of the inner class.
Classification and commonality of inner classes:
Commonality:
- An inner class is still an independent class. After compilation, the inner class is compiled into an independent `.class` file, but it is prefixed with the outer class name and the `$` symbol.
- Inner classes cannot be accessed in the normal way. An inner class is a member of the outer class, so it can freely access the member variables of the outer class, whether they are private or not.
Member inner class
In the outer class there are member variables and member methods; a member inner class treats an entire class as a member of the outer class.
A member inner class is definedinside the class but outside the methodsof the class.
The format for creating an object is:`OuterClassName.InnerClassName objectName = outerClassObject.innerClassObject`;
The reason a member inner class can directly access members of the outer class is that the inner class holds a reference to an outer class object:`OuterClassName.this`;
The modifiers that can be used for member inner classes are `final`, `abstract`, `public`, `private`, `protected`, `static`.
Static inner class
A static inner class is a member inner class with the static modifier `static`, definedinside the class but outside the methods.。
There are two scenarios for accessing a static inner class from the outer class:
- Accessing non-static members of a static inner class from the outer class:`*OuterClassName.InnerClassName objectName = OuterClassName.innerObject*`You need to access it by creating an object;
- Accessing static members of a static inner class from the outer class: you can also use the above format, or directly use`OuterClassName.InnerClassName.member`。
Local inner class
A local inner class is a class defined inside a method.
- A method inner class can only be instantiatedinside the method in which it is definedand cannot be instantiated outside this method.
- A method inner class object cannot use non-final local variables of the method in which the inner class is located.
The modifiers that can be used for a method inner class arefinal,abstract;
A method inner class in a static method can only accessthe outer static members。
Anonymous inner class
An anonymous inner class is a simplified form of an inner class; it creates an anonymous subclass object with content that inherits an outer class or implements an interface.
Prerequisite:
An inner class can inherit or implement an outer class or interface.
Format:
`new OuterClassNameOrInterfaceName() { override methods };`
Usually, when a method's formal parameter is an interface or an abstract class, and the interface has no more than three methods, an anonymous inner class can be passed as an argument.
Content modified by different modifiers (unrelated to inner classes)
| Class | Member variables | Member methods | Constructors | |
|---|---|---|---|---|
| private | Y | Y | Y | |
| Default | Y | Y | Y | Y |
| protected | Y | Y | Y | |
| public | Y | Y | Y | Y |
| abstract | Y | Y | ||
| static | Y | Y | Y | |
| final | Y | Y | Y |
Note, common rules are as follows:
- In the future, all classes should be modified with `public`. Also, in one Java file, only one class should be written.
- In the future, all member variables should be modified with `private`.
- In the future, all member methods should be modified with `public`.
If it is an abstract class or interface: `public abstract` + ... - From now on, all constructors should be modified with public.
If the class is a utility class or a singleton class: use private to modify the constructor.
Four access modifiers
| Same class | Same package (unrelated classes or subclasses) | Different package (subclasses) | Different package (unrelated classes) | |
|---|---|---|---|---|
| private | Y | |||
| Default | Y | Y | ||
| protected | Y | Y | Y | |
| public | Y | Y | Y | Y |
Recommendation:
- Member variables: private
- Constructor: public
- Member methods: public
More tutorials
For more detailed tutorials, refer to:Java Tutorial
Source: http://www.codeceo.com/article/java-extends.html