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 } }
如果子類中沒有定義覆蓋方法,則會調(diào)用父類中的方法:
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(); } }
【運行結(jié)果】:
Person.eat()
2.靜態(tài)方法的綁定
將上面的方法都加上static關(guān)鍵字,變成靜態(tài)方法:
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(); } } }
【運行結(jié)果】:
Person.eat() Person.eat() Person.eat() Person.eat()
觀察結(jié)果,對于靜態(tài)方法而言,不管父類引用指向的什么子類對象,調(diào)用的都是父類的方法。
更多java相關(guān)文章請關(guān)注java基礎(chǔ)教程欄目。
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac

defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability.

Choosing the right HTMLinput type can improve data accuracy, enhance user experience, and improve usability. 1. Select the corresponding input types according to the data type, such as text, email, tel, number and date, which can automatically checksum and adapt to the keyboard; 2. Use HTML5 to add new types such as url, color, range and search, which can provide a more intuitive interaction method; 3. Use placeholder and required attributes to improve the efficiency and accuracy of form filling, but it should be noted that placeholder cannot replace label.
