Today, I visited the company as usual. Sit down at your workstation and turn on the computer, "It's another day of moving bricks". After thinking about it, I opened Idea skillfully, looked at today's requirements, and started typing the code. Hey, who wrote these codes, how come they appear in my code, and they are still waiting to be submitted. I remember I have never written them, so I looked at them with interest:
Isn’t this polymorphic? Whoever wrote the test on my computer couldn’t help but wonder. "Look at the output of this?"
A sound came from behind. Because I was thinking about the output, I didn't care about the source of the sound, so I continued. After looking at the code, I came to the conclusion:
polygon() before cal()
square.cal(), border = 2
polygon() after cal()
square.square(), border = 4復(fù)制代碼
I thought: That’s it? At least you are a Java development engineer, okay? Although you usually do a lot of work, you still have some basic skills. I couldn't help but feel a little proud~
"Is this your answer? It seems that you are not doing well either"
The voice suddenly sounded again, this time I was not calm anymore , Nima! I also thought about this answer in my mind, okay? Who can see it? Moreover, it makes people want to perform a set of Awei's Eighteen Styles.
"Who are you?"
turned his head with a hint of doubt and anger. Why is there no one? I couldn't tolerate any doubts, "Xiaocai, wake up, why did you fall asleep during working hours?"Did you fall asleep during working hours? I opened my eyes and looked at my surroundings. It turned out to be a dream, and I breathed a sigh of relief. I looked around and saw the department manager standing in front of me. He was sleeping during working hours. Are you feeling unwell or something? I wrote a bunch of bugs yesterday but didn't correct them, and I submitted some messy stuff today. I think your performance this month is not what I want, and based on your performance, I have to start thinking about it for the department.
"I'm not, I didn't, I don't know why I fell asleep, please listen to my explanation!"
Before I could say this sentence, felt in my heart I want to take you home with the flower. I don’t care if it’s real or fake in the bar late at night. Please swing it to your heart’s content and forget about him. You are the most charming. Do you know? The alarm bell rang. I I stood up, my back was slightly wet, my forehead was slightly sweaty, I checked my phone, it was Saturday, 8:30, it turned out to be a dream! Strange, how could I have such a strange dream? It’s so scary. Then I thought of the part of the code in the dream. Are my results wrong? Based on memory, I typed it out again on the computer, and the results are as follows:
/*
polygon() before cal()
square.cal(), border = 0
polygon() after cal()
square.square(), border = 4
*/復(fù)制代碼
square.cal(), the result of border
is actually 0, not 2. Am I not even good at polymorphism now? In front of your computer and mobile phone, you don’t know if you have come up with the correct answer! Regardless of whether you have it or not, let’s review polymorphism with Xiao Cai!
Some friends may be confused about not only the result of square.cal(), border
is 0, but also why it is not
square.square(), border = 4 Output the doubts first. Then let’s get started with doubts! Polymorphism
In object-oriented programming languages, polymorphism is the third basic feature after data abstraction and inheritance.
Polymorphism can not only improve the organization and readability of code, but also create scalable programs. The function of polymorphism is to eliminate the coupling relationship
between types.
1. Upward transformation
According to the
Richter substitution principle
: Wherever a base class can appear, a subclass can definitely appear.
The object can be used either as its own type or as its base type. This method of treating a reference to an object as a reference to its base type is called - Upcast
. Because the parent class is above the child class, the child class must reference the parent class, so it is called
Upward transformation.
public class Animal { void eat() {
System.out.println("Animal eat()");
}
}class Monkey extends Animal { void eat() {
System.out.println(" Monkey eat()");
}
}class test { public static void start(Animal animal) {
animal.eat();
} public static void main(String[] args) {
Monkey monkey = new Monkey();
start(monkey);
}
}/* OUTPUT:
Monkey eat()
*/復(fù)制代碼
The start() method in the above
test class receives a reference to Animal, and naturally can also receive from Animal's exported class. When calling the eat() method, the eat() method defined in Monkey is naturally used without any type conversion. Because upgrading from Monkey to Animal can only reduce the number of interfaces, but not fewer interfaces than Animal. A not particularly appropriate analogy: Your father’s property will be inherited to you, and your property is still yours. In general, your property will not be less than your father’s.
靜態(tài)綁定:又稱為前期綁定。是在程序執(zhí)行前進(jìn)行把綁定。我們平時(shí)聽(tīng)到"靜態(tài)"的時(shí)候,不難免想到static關(guān)鍵字,被static關(guān)鍵字修飾后的變量成為靜態(tài)變量,這種變量就是在程序執(zhí)行前初始化的。前期綁定是面向過(guò)程語(yǔ)言中默認(rèn)的綁定方式,例如 C 語(yǔ)言只有一種方法調(diào)用,那就是前期綁定。
引出思考:
public static void start(Animal animal) {
animal.eat();
}復(fù)制代碼
class Super { public int field = 0; public int getField() { return field;
}
}class Son extends Super { public int field = 1; public int getField() { return field;
} public int getSuperField() { return super.field;
}
}class FieldTest { public static void main(String[] args) {
Super sup = new Son();
System.out.println("sup.field:" + sup.field + " sup.getField():" + sup.getField());
Son son = new Son();
System.out.println("son.field:" + son.field + " son.getField:" + son.getField() + " son.getSupField:" + son.getSuperField());
}
}/* OUTPUT
sup.field:0 sup.getField():1
son.field:1 son.getField:1 son.getSupField:0
*/復(fù)制代碼
從上面代碼中我們看到sup.field輸出的值不是 Son 對(duì)象中所定義的,而是Super本身定義的。這與我們認(rèn)識(shí)的多態(tài)有點(diǎn)沖突。
The above is the detailed content of These days, if you say you know Java, you have to know polymorphism.. For more information, please follow other related articles on the PHP Chinese website!
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
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
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
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.