Basic concepts of java inheritance and synthesis
Inheritance: You can construct a new class based on an existing class. Inheriting existing classes allows you to reuse the methods and fields of these classes. On this basis, new methods and fields can be added, thereby expanding the functionality of the class.
Synthesis: Creating an original object in a new class is called synthesis. This way you can reuse existing code without changing its form.
Recommended related video tutorials: java video tutorial
1. Inherited syntax
The keyword extends indicates that the new class is derived to an existing class. The existing class is called a parent class or base class, and the new class is called a subclass or derived class. For example:
class Student extends Person { }
The class Student inherits Person. The Person class is called the parent class or base class, and the Student class is called the subclass or derived class.
2. Syntax of synthesis
Synthesis is relatively simple, which is to create an existing class within a class.
class Student { Dog dog; }
Updating modeling
1. Basic concept
The role of inheritance lies in the duplication of code use. Since inheritance means that all methods of the parent class can also be used in the child class, messages sent to the parent class can also be sent to the derived class. If there is an eat method in the Person class, then there will also be this method in the Student class, which means that the Student object is also a type of Person.
class Person { public void eat() { System.out.println("eat"); } static void show(Person p) { p.eat(); } } public class Student extends Person{ public static void main(String[] args) { Student s = new Student(); Person.show(s); // ① } }
[Run results]:
eat
The show method defined in Person is used to receive the Person handle, but what is received at ① is a reference to the Student object. This is because the Student object is also a Person object. In the show method, the incoming handle (object reference) can be a Person object and a Person-derived class object. This behavior of converting a Student handle into a Person handle is called upcasting.
2. Why do we need to trace back the shape?
Why do we intentionally ignore the object type that calls it when calling eat? It seems more intuitive and easier to understand if the show method simply obtains the Student handle, but that would cause each new class derived from the Person class to implement its own show method:
class Value { private int count = 1; private Value(int count) { this.count = count; } public static final Value v1 = new Value(1), v2 = new Value(2), v3 = new Value(3); } class Person { public void eat(Value v) { System.out.println("Person.eat()"); } } class Teacher extends Person { public void eat(Value v) { System.out.println("Teacher.eat()"); } } class Student extends Person { public void eat(Value v) { System.out.println("Student.eat()"); } } public class UpcastingDemo { public static void show(Student s) { s.eat(Value.v1); } public static void show(Teacher t) { t.eat(Value.v1); } public static void show(Person p) { p.eat(Value.v1); } public static void main(String[] args) { Student s = new Student(); Teacher t = new Teacher(); Person p = new Person(); show(s); show(t); show(p); } }
This approach is obvious The disadvantage is that closely related methods must be defined for each derived class of the Person class, resulting in a lot of duplicate code. On the other hand, if you forget to overload a method, no error will be reported. The three show methods in the above example can be combined into one:
public static void show(Person p) { p.eat(Value.v1); }
Dynamic binding
When show(s) is executed, The output result is Student.eat(), which is indeed the desired result, but it does not seem to be executed in the form we want. Let’s take a look at the show method:
public static void show(Person p) { p.eat(Value.v1); }
It receives the Person handle. When executed When show(s), how does it know that the Person handle points to a Student object instead of a Teacher object? The compiler has no way of knowing, which involves the binding issue explained next.
1. Binding of method calls
Connecting a method with a method body is called binding. If binding is performed before running, it is called "early binding". In the above example, when there is only one Person handle, the compiler does not know which method to call. Java implements a method calling mechanism that can determine the type of an object during runtime and then call the corresponding method. This binding, which is performed during runtime and is based on the type of the object, is called dynamic binding. Unless a method is declared final, all methods in Java are dynamically bound.
Use a picture to represent the inheritance relationship of upstream modeling:
Summarize it in code:
Shape s = new Shape();
According to the inheritance relationship, create It is legal to assign the Circle object handle to a Shape because Circle is a type of Shape.
When one of the base class methods is called:
Shape s = new Shape();
At this time, Circle.draw() is called, which is due to dynamic binding.
class Person { void eat() {} void speak() {} } class Boy extends Person { void eat() { System.out.println("Boy.eat()"); } void speak() { System.out.println("Boy.speak()"); } } class Girl extends Person { void eat() { System.out.println("Girl.eat()"); } void speak() { System.out.println("Girl.speak()"); } } public class Persons { public static Person randPerson() { switch ((int)(Math.random() * 2)) { default: case 0: return new Boy(); case 1: return new Girl(); } } public static void main(String[] args) { Person[] p = new Person[4]; for (int i = 0; i < p.length; i++) { p[i] = randPerson(); // 随机生成Boy或Girl } for (int i = 0; i < p.length; i++) { p[i].eat(); } } }
Person has established a common interface for all classes derived from Person, and all derived classes have two behaviors: eat and speak. Derived classes override these definitions, redefining both behaviors.
In the main class, randPerson randomly selects the handle of the Person object. **Appeal shaping occurs in the return statement. The **return statement obtains a Boy or Girl handle and returns it as a Person type. At this time, we don’t know the specific type, we only know that it is a Person object handle.
Call the randPerson method in the main method to fill in the Person object into the array, but I don’t know the specific situation. When the eat method of each element of the array is called, the role of dynamic binding is to execute the redefined method of the object.
However, dynamic binding has a prerequisite. The binding method must exist in the base class, otherwise it cannot be compiled.
class Person { void eat() { System.out.println("Person.eat()"); } } class Boy extends Person { void eat() { System.out.println("Boy.eat()"); } void speak() { System.out.println("Boy.speak()"); } } public class Persons { public static void main(String[] args) { Person p = new Boy(); p.eat(); p.speak(); // The method speak() is undefined for the type Person } }
如果子类中没有定义覆盖方法,则会调用父类中的方法:
class Person { void eat() { System.out.println("Person.eat()"); } } class Boy extends Person { } public class Persons { public static void main(String[] args) { Person p = new Boy(); p.eat(); } }
【运行结果】:
Person.eat()
2.静态方法的绑定
将上面的方法都加上static关键字,变成静态方法:
class Person { static void eat() { System.out.println("Person.eat()"); } static void speak() { System.out.println("Person.speak()"); } } class Boy extends Person { static void eat() { System.out.println("Boy.eat()"); } static void speak() { System.out.println("Boy.speak()"); } } class Girl extends Person { static void eat() { System.out.println("Girl.eat()"); } static void speak() { System.out.println("Girl.speak()"); } } public class Persons { public static Person randPerson() { switch ((int)(Math.random() * 2)) { default: case 0: return new Boy(); case 1: return new Girl(); } } public static void main(String[] args) { Person[] p = new Person[4]; for (int i = 0; i < p.length; i++) { p[i] = randPerson(); // 随机生成Boy或Girl } for (int i = 0; i < p.length; i++) { p[i].eat(); } } }
【运行结果】:
Person.eat() Person.eat() Person.eat() Person.eat()
观察结果,对于静态方法而言,不管父类引用指向的什么子类对象,调用的都是父类的方法。
更多java相关文章请关注java基础教程栏目。
The above is the detailed content of Detailed explanation of inheritance in Java. For more information, please follow other related articles on the PHP Chinese website!