Dark Horse Programmer--java Foundation-polymorphic

Source: Internet
Author: User
Tags define abstract modifiers

------Java Training, Android training, iOS training,. NET training, look forward to communicating with you! -------

Template Method Design Pattern:
Solution: When the internal part of the function is a reality to determine, part of the reality is uncertain, this time should not be uncertain part of the leak out, let the sub-class implementation.
Example: Counting the run time of a program
Idea: The end time of the program minus the start time of the program

Abstract class Gettime{public final void Gettime () {//This function uses final to limit long start = System.currenttimemillis (); runtime ();// This part of the function is not deterministic, extracted, through the abstract method to achieve long end = System.currenttimemillis (); System.out.println ("Te Time:" + (End-start));} public abstract void Runtime ();//abstract indeterminate function, let sub-class replication implementation}class Demo extends gettime{public void runtime () {//Sub-class Replication function method for (int i= 0; i<1000; i++) {System.out.println (i);}}}

Interface:
1. Decorate with interface keyword
2. The members included in the interface, the most common are global variables, abstract methods
Note: Members in an interface have fixed modifiers
Member variable: public static final
Member Method: Public abstract
Interface inter{
public static final int x = 3;
publicabstract void Show ();
}
3. The interface has an abstract method, indicating that the interface is not instantiated, the sub-class of the interface must implement all the abstract methods in the interface, the subclass can be instantiated, otherwise, the subclass is an abstract class.
4. There is an inheritance relationship between classes and classes, and there is an implementation relationship between classes and interfaces
Inheritance with extends
Implementation with implements
5. Interfaces and classes are not the same place is the interface can be implemented more, this is the result of multiple inheritance improvement, Java will multi-inheritance mechanism through a multi-implementation to reflect

Class A{void Show () {System.out.println ("A");}} Class B{int num = 3;void print () {System.out.println (num);}} Class C extends a,b{//this is wrong, classes can not be more inherited, mentioned before} but can be embodied through the multi-implementation of the interface: abstract class a{public abstract void Show () { System.out.println ("a");}} Abstract class B{public static final int num = 3;public abstract void print () {System.out.println (num);}} Class C implements a,b{//such a correct}6. A class can implement multiple interfaces while inheriting a class, so the interface avoids the limitations of single inheritance and can also extend the functionality of the class. Class a{public void Show () {System.out.println ("A");}} Ieterface class b{public static final int num = 3;public abstract void print () {System.out.println (num);}}
Class C extends A implements b{
This is possible, inheriting a class and extending the functionality through the interface
}
7. In fact, there are many inheritance in Java, but there are many inheritance between interfaces, interfaces can inherit more interfaces, the other things do not have this property
Interfaces are used in the design, the characteristics of the design:
1. Interface is a rule provided externally
2. Interface is an extension of the function
3. The appearance of the interface reduces the coupling
Abstract classes and Interfaces:
Abstract class: Generally used to describe a system unit, a set of common content to extract, features: You can define abstract content in the class to allow subclasses to implement, you can define non-abstract content so that subclasses directly use, it is defined in some of the basic content of the system.
Interface: It is generally used to define the extended functionality of an object, but rather to have some functionality beyond inheritance.
The commonality of objects and interfaces: The result of continuous upward extraction


The difference between an abstract class and an interface:
1. Abstract classes can only be inherited, and can only be inherited by sheets.
Interfaces need to be implemented and can be implemented more
2. Non-abstract methods can be defined in an abstract class, and subclasses can be used directly for inheritance.
There are abstract methods in the interface that require subclasses to implement
3. Abstract class uses the relationship of is a
The interface uses the like a relationship
4. Member modifiers for abstract classes can be customized
The member modifiers in the interface are fixed, all public
The interface reduces the direct coupling!
Interface Examples:

class person {void sleep () {System.out.println ("Sleeping in Bed");} This is the generality of}interface class inter{abstract void smoking ();//This is the attribute abstract void drink ();//This is an attribute, which can also be independent of an interface}class Smallstudent extends Person{}class bigstudent extends person inplememts{smoking () {System.out.println ("smooking");} Drink () {System.out.println ("drinking");}} public class Interdemo{public static void Main (String args[]) {Smoking s = new smoking (); System.out.println (s);}} 
Polymorphic:
Embodiment: A reference to a parent class or interface that points to its own subclass object
A reference to the parent class points to its own subclass object.
A reference to a parent class can also receive its own subclass object//animal cat = new Cat ();
The benefits of polymorphism: Improved code scalability
The disadvantage of polymorphism: when the parent class refers to a subclass object, it improves extensibility, but only accesses the methods that the parent class has, and does not have access to the methods that are unique to the subclass (late-generation functionality cannot be used in the early stages, and access limitations)
Prerequisites for polymorphism:
1. Must have a relationship, such as inheriting or implementing
2. There is usually a overwrite operation
The realization of polymorphism is also changing: The former is to create objects and command objects to do things, after abortion, we can find the common types of objects, directly manipulate common types to do things, so you can direct a group of objects to do things, that is, by manipulating the parent class or interface implementation


Polymorphism: Can be understood as the existence of a variety of forms of expression.
Man: Man, woman
Animals: cats, dogs.
Cat x = new Cat ();
Animal x = new Cat ();

Abstract class Animal{abstract void sleep ();//Common features}class Cat extends Animal{sleep () {System.out.println ("Morning Sleep" );} public void Catchmouse () {///separate attribute System.out.println ("Catchmouse");}} Class Dog extends Animal{sleep () {System.out.println ("Night Sleep");} public void Yaoren () {System.out.println ("Yaoren");}} public class Duotaidemo{public static void Main (String agrs[]) {Cat c = new Cat (); C.sleep (); C.catchmouse ();D og d = new Dog ( );d. Sleep ();d. Yaoren ();} This is OK, but the extensibility is poor, because cats and dogs are animals, they have common attributes,//When creating objects can be created using animal, and if there are new animals added to the operation more troublesome public static void function (Cat c) {C.sleep ();} public static void function (Dog d) {d.sleep ();}} We can consider this, public static void function (Cat c) {c.sleep ();} public static void function (Dog d) {d.sleep ();} Simplify this code: public static void Function (Animal a) {//here Animal A = new Cat ()/dog () A.sleep ();} The main function can write this: public class Duotaidemo{public static void Main (String agrs[]) {function (new Cat); A.sleep (); A.catchmouse (); function (new Dog); A.sleep (); A.yaoren ();}} Example two: Class A{void learn () {SYSTEM.OUT.PRINTLN ("Learn Chinese");} void Habit () {System.out.println ("play Pingpang");}} Class B extends A{void learn () {System.out.println ("learn 中文版");} void Write () {System.out.println ("Write Code");}} Class Demo{public static void Main (String args[]) {A A = new B ();//Upward transformation A.learn (); A.write ();//This is wrong, the parent class does not have the function of subclasses// What do I do if I want to invoke the cat's unique method? Forces a reference to the parent class. Turn into a subclass type. Downward transformation. b b = (b) a;//downward transition b.write ();//Do not do this, that is, the parent class object to the subclass type. What we can convert is that when the parent application points to its own subclass object, the app can be promoted or cast. Polymorphism is a subclass of objects that are changing from beginning to finish. }}
Involving knowledge points: upward transformation and downward transformation
Instanceof: Used to determine the type of object. Object intanceof type (class type interface type)
Student instanceof person = true;//student inherits the Person class
The characteristics of polymorphism in the members of the Child parent class:
1. Member variable: Too much weight, child parent class member variable with the same name
At compile time: Refer to whether the referenced variable belongs to the tired member that has the call
Run time: is also the member that is called in the class to which the reference type variable belongs
A simple sentence: whether compiled or run, member variables refer to member variables in the class that the reference variable belongs to
That is, the compilation run looks to the left
2. member functions
Compile time: Reference type variable belongs to the tired of whether there is a call place
Runtime: Refers to whether the object belongs to the tired of the call method
Why is that so? Because in the child parent class, there is one feature for a touch-like member function: overwrite
Simple sentence: member function, compile to see the class that the reference variable belongs to, run to see the class that the object belongs to
That is: member function compilation look to the left, run look right
3. Static functions:
Compile time: Reference to whether the referenced variable belongs to a class that has a calling member
Run time: is also a member of a class that refers to a reference-type variable that has a call
Why is that? Because a static method does not belong to an object, it belongs to the class where the method resides
Simply put: the static function has run and looks to the left

Package Code;class Fu{int num = 4;void Show () {System.out.println ("Fu");} void print () {System.out.println ("num:" +num);} public static void Method () {System.out.println ("Fu.method");}} Class Zi extends Fu{int num = 5;void Show () {System.out.println ("Zi");} public static void Method () {System.out.println ("Zi.method");}} public class Duotaidemo {public static void main (String args[]) {Fu a = new Zi (); a.show ();//zia.print ();//num:4a.method (); Fu.method}}
Summary: Member variables run results look left
member function run results look right
Static function Run results look to the left

Example: Motherboard
Analysis: The computer has a motherboard can be run up, can surf the internet, listen to music, etc., but these features are motherboard cloth with, only through the external network card and sound card to expand, in order to improve the scalability, you need to have a slot, PCI.
1. You can use PCI on the motherboard and then use PCI to extend the network card and sound card features
2. Network card and sound card to define their own functions
3. Complete

Class Mainboard () {Mainopen () {System.out.println ("Mainopen");} Mainclose () {System.out.println ("Mainclose");} MAINUSEPCI (PCI p) {if (PCI! = null) {P.open ();p. Close ();}} Interface Pci{public abstract void open ();p ublic abstract void Close ();} Class Netcard implements pci{public Void Open () {System.out.println ("netcard Open");} public void Close () {System.out.println ("netcard close");}} Class Soundcard implements pci{public Void Open () {System.out.println ("Soundcar Open");} public void Close () {System.out.println ("Soundcar close");}} public class Mainboarddemo{public static void Main (String args[]) {mainboard m = new mainboard (); M.open (); M.mainusepci ( New netcard ()); M.mainusepci (new Soundcard ());}} Object: is the direct latter indirect parent of all objects. What is defined in this class is definitely the functionality that all objects have. The object class already provides a comparison method for whether the objects are the same. If the custom class also has the same functionality, there is no need to redefine it. Just follow the functions in the parent class and build your own unique comparison, which is the overlay. Involving Knowledge points: 1.equals2.instanceof3.tostring () 4.object Compare two objects: Class Demo{void Show () { System.out.println ("Demo");}} Class Objectdemo{public static Vodi main (String args[]) {Demo D1 = new demo ();D emo D2 = new Demo (); System.out.println (D1.equals (D2));//output false because D1 and D2 address are different//equals usage: d1.equals (d2)}} compare two member variables: Class Demo{private int num = 4;demo (int num) {this.num = num;} public boolean equals (Object obj) {Demo d = (demo) Obj;return this.num = = D.num;}} Class Objectdemo{public static Vodi main (String args[]) {Demo d = new demo ();}}



Dark Horse Programmer--java Foundation-polymorphic

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.