JAVA basics-three major object-oriented features: encapsulation, inheritance, polymorphism, and java
JAVA object-oriented features 1. Encapsulation
1. concept:
Some information of the class is hidden inside the class, and external programs are not allowed to directly access it. Instead, the class provides methods to operate and access the hidden information.
2. Benefits:
- You can only access data using specified methods.
- Hides the instance details of the class for convenient modification and implementation.
3. encapsulation steps
Note: you do not have to use the get/set Method for encapsulated attributes. Other methods can also operate on encapsulated attributes. Of course, it is best to use the get/set method, which is more standard.
A. Access Modifier
From the table, we can see thatPackage from top to bottom is getting worse.
B. this keyword
1. this keywordRepresents the current object
This. Attribute operation on the attributes of the current object
This. The method calls the method of the current object.
2. this keyword is often used when encapsulating object attributes.
3. When the parameter names of the getter and setter functions overlap with those of the member functions,You can use thisDifference. For example:
C. Internal classes in Java
An Inner Class is defined in another Class.Inside. Classes that contain internal classes are called external classes.
So the question is: why should a class be defined in another class? How nice it is to be a clear and standalone independent class !!
A: The main functions of internal classes are as follows:
1. The internal class providesBetter Encapsulation, You can set the internal classHideWithin the external class,Not AllowedOther classes in the same package access this class.
2. Internal class methods are acceptable.Directly access all data of the external class, IncludingPrivate Data.
3. functions implemented by internal classes can also be implemented using external classes, but sometimes internal classes are more convenient.
Internal classes can be divided into the following types:
-
- Member internal class
- Static internal class
- Internal method class
- Anonymous internal class
Specific Use of each internal class is transferred to another article: http://www.cnblogs.com/hysum/p/7101974.html
Ii. Inheritance 1. Concept of Inheritance
Inheritance is a relationship between classes and classes. It is a "is a" relationship. For example, "dogs" inherit "Animals", where animals are the parent class or base class of dogs, and dogs are subclasses or derived classes of animals. As shown in:
Note: The Inheritance in java isSingle inheritance, That isA class has only one parent class.
2. Benefits of Inheritance
Sub-classes have all attributes and methods of the parent class (except those modified by the private class), thus implementing code reuse;
3,Syntax RulesYou only need to add the extends keyword to the subclass to inherit the corresponding parent class:
A. Method Rewriting
If the subclass is not satisfied with the method of the inherited parent class (not suitable), you can compile the inherited method by yourself. This method is calledMethod override. When a method is called, The subclass method is called first.
Note:
A. Return Value Type
B. Method Name
C. parameter types and quantity
It must be the same as the method inherited by the parent class.
Differences between heavy load and rewrite:
Method overload: multi-state means for processing different data in the same class with the same method name.
Method Rewriting: For inheritance, modify the existing methods of the parent class in the subclass.
B. Inheritance initialization sequence
1. initialize the parent class and then initialize the subclass.
2. First, execute the attributes in the initialization object, and then execute the initialization in the constructor.
Based on the above two points, we know that the execution sequence of java programs is:
Parent Class Object Property initialization ----> parent class object construction method ----> subclass Object Property initialization ---> subclass Object Construction Method
The following figure shows an image:
C. final keywords
Using the final keyword for identification has the "final" meaning.
1. final modifier class, then this classInheritance is not allowed.
2. The final modification method is not allowed.Overwrite).
3. If the final attribute is modified, the attribute of this class will not be implicitly initialized.The initialization property must have a value., Or inAssign values in the constructor (but only one of them is required, because no default value exists !),And cannot be changed after initialization,Only one value can be assigned..
4. If the final variable is modified, the value of the variable can only be assigned once and assigned only when the variable is declared.Constant.
D, super keyword
Internal use of the object can represent the parent class object.
1. Access the attributes of the parent class: super. age
2. Method for accessing the parent class: super. eat ()
Super applications:
First, we know that the constructor of the parent class must be called during subclass construction. In fact, our super keyword has been implicitly used in this process.
This is because if the constructor of the subclass does not display the constructor that calls the parent class, the system calls the constructor without parameters by default.
If you use the super keyword to call the constructor of the parent class in the subclassFirst line.
Note: If the subclass constructor does not display the constructor that calls the parent class, but the parent class does not have a constructor without parameters, a compilation error occurs.
(Note: although no constructor that declares no parameters for the parent class is displayed, the system automatically generates a constructor without parameters by default. However, if you declare a constructor with parameters, without declaring a constructor without parameters, the system will not generate a constructor without parameters by default. In this case, it is called whether the parent class has a constructor without parameters .)
E. Object Class
The Object class is the parent class of all classes. If a class does not use the extends keyword to explicitly identify the inheritance of another class, this class inherits the Object class by default.
Methods In the Object class, suitable for all subclasses !!!
What are the main methods in the Object class?
1. toString ()
A. the hash code (Object address string) of the returned Object when the toString () method is defined in the Object class ).
We can find that if we use System. out. print (object) to output an object directly, the running result outputs the object address string of the object, also known as the hash code. For example:
A hash code is a string generated by the hash algorithm. It is usedUniqueDistinguish the address code of our object, just like our ID card.
B. You can override toString () to indicate the attributes of an object.
If we want to output an object, instead of its hash code, but its attribute values, we can rewrite toString () to indicate its attributes.
2. equals ()
A, equals () ---- return value is boolean type.
B. By default, objects are comparedReferenceWhether to point to the same memory address ------- when the object is instantiated, it allocates memory space to the object. The address of the memory space is the memory address. Usage example: dog. equals (dog2 );
C. If two objects have the same attributes, rewrite the equals () method.
Take the Dog class as an example. The overwritten equals () method is as follows (of course, you can rewrite the equals () method based on the property you want to compare. Here I will rewrite the equals () method with the same age property):
There are four judgments on them. Their meanings are as follows:
1. Check whether the address is the same ---- if (this = obj). if the address is the same, true is returned.
2. Determine whether the object is null ---- if (obj = null). if it is null, false is returned.
3.GetClass () can get the Class ObjectTo determine whether the type is the same ----- if (getClass ()! = Obj. getClass (). If it is different, false is returned.
4. Determine whether the attribute value is the same ---- if (age! = Other. age). Otherwise, false is returned.
5. If the address is the same, the object is not empty, the type is the same, and the property value is the same, true is returned.
Note that the differences between class objects and class objects obtained by obj. getClass () are as follows:
We can see that for class objects, we care about which class it belongs to and what attributes and methods it has. For example, both me and you belong to the class Object "person; the class object is a specific object of class instantiation. For example, you and I are two different people.
Iii. Polymorphism
The last feature of object-oriented is polymorphism. What is polymorphism? Polymorphism isMultiple forms of objects.
Java polymorphism mainly involves two aspects:
1. Reference Polymorphism
The reference of the parent class can point to the object of this class;
A reference to a parent class can point to a subclass object;
What are the meanings of these two statements? Let's use the code to try it out. First, we create a parent class Animal and a subclass Dog, as shown in the main function:
Note: we cannot use a subclass reference to point to the parent class object, for example :.
Here, we must have a deep understanding of the significance of referencing polymorphism to better remember this polymorphism. Why can't subclass references point to the objects of the parent class? Here I would like to explain it to you: In the above example, we can say that "A dog is an animal", but it cannot be said that "an animal is a dog ", dogs and animals are inherited from parent classes and child classes, and their subordination cannot be reversed. When the reference of the parent class points to the object of the subclass, the object will only be regarded as a special parent class (which contains override methods and attributes). Otherwise, it is not feasible to reference a subclass to point to the object of the parent class !!
2. Method Polymorphism
Based on the two objects created above: the class object and the subclass object are also referenced by the parent class. When we direct to different objects, the methods they call are also polymorphism.
The method called when creating this class object is this class method;
When a subclass object is created, the method called is the method rewritten by the subclass or the inherited method;
Note the following when using polymorphism:If we compile a unique method in the subclass (without inheriting the method of the parent class), we cannot call this method by referencing the created subclass object of the parent class !!!
Note: inheritance is the basis of polymorphism.
A. Conversion of reference types
After understanding the meaning of polymorphism, we often need to convert the reference type when using polymorphism features.
Conversion of reference types:
1.Upward type conversion(Implicit/automatic type conversion), small type conversion to large type.
As described above, the parent class Animal and a subclass Dog indicate that when the parent class reference can point to the subclass objectUpward type conversion. For example:
2.Downward type conversion(Forced type conversion) is a conversion from a large type to a small type (risky, data overflow may occur ).
Adding a line of the above Code and converting the parent class into a subclass reference will cause an error. The Compiler does not allow us to do this directly.,Although we know that this parent class references a subclass object, the compiler considers this conversion to be risky..For example:
So how can we solve this problem? We can add (Dog) before animal to force type conversion. For example:
However, if the parent class does not pointObject of this subclass, The type cannot be converted downward. Although the compiler does not report errors, the program will encounter errors during running, such:
In fact, this is the reference of the subclass mentioned above pointing to the object of the parent class, and the forced conversion type cannot be converted !!
Another case is that the reference of the parent class pointsObjects of other subclass, Cannot be convertedObject of this subclass. For example:
This is because we forced type conversion during compilation, and the type during compilation is the type we forced conversion, so the compiler will not report an error, and when we run, the program opens up Dog-type memory space for animal, which does not match Cat-type memory space and thus cannot be converted normally. These two kinds of errors are essentially the same, so we should pay special attention to these two errors when using forced type conversion !! Below is a safer way to achieve downward type conversion ....
3. instanceof operator,To solve the type of the referenced object and avoid the security problem of type conversion.
InstanceofIs a binary operator of Java, and is equal to =, >,<. Because it is composed of letters, it is also a reserved keyword of Java.It is used to test whether the object on the left is an instance of the class on the right of the object., Returns boolean data.
We use the instanceof operator to avoid the above errors. The code is modified as follows:
Use the if statement and instanceof operator to determine whether the types of the two objects are consistent.
Note:When comparing whether an object and another object belong to the same class instance, we can usually use the instanceof and getClass methods to determine whether the two are equal, however, there is a difference between the two. Instanceof:Do you belong to this class? Or do you belong to the derived class of this class?The getClass method is used to obtain the type information and = is used to check whether the operation is equal.Strict judgment,There will be no inheritance considerations;
Summary:When writing a program, if you want to perform type conversion, we 'd better use the instanceof operator to determine whether the object on the left is an instance of the class on its right and then perform forced conversion.
B. abstract class
Definition: If abstract keywords are used before an abstract class, the class is an abstract class.
Note the following when using abstract classes:
1. An abstract class is a method required to restrict subclass, rather than how the subclass implements these methods.
2. Application scenarios of abstract classes:
A. In some cases, a parent class only knows how its subclass should contain, but cannot accurately know how these subclasses implement these methods (Dynamic polymorphism can be implemented ).
B. Abstract An abstract class from multiple classes with the same features and use this abstract class as the template of the subclass to avoid the randomness of the subclass design.
3. Abstract Classes define abstract methods. They only have declarations and do not need to be implemented. Abstract methods do not end with semicolons. abstract methods must be modified with abstract keywords. For example:
4. classes that contain abstract methods are abstract classes. Abstract classes can contain common methods or abstract methods. For example:
5. abstract classes cannot be directly created. You can define reference variables to point to subclass objects to implement abstract methods. The preceding Telephone abstract class is used as an example:
1 public abstract class Telephone {2 public abstract void call (); // The abstract method. The method body ends with a semicolon and is declared only. 3 public void message () is not required () {4 System. out. println ("I am a normal method of an abstract class"); 5} // The abstract class contains a normal method 6}
1 public class Phone extends Telephone {2 3 public void call () {// The subclass of the inherited abstract class must override the abstract method 4 // TODO Auto-generated method stub5 System. out. println ("I have rewritten the abstract class method"); 6} 7 8}
The above is the definition of the Telephone abstract class and the sub-class Phone. Let's look at the main function:
Running result (after troubleshooting ):
C. Interface
1. Concepts
The interface can be understood as a special classGlobal constantAnd publicAbstract Method. It can also be understood as a special abstract class because it contains abstract methods.
If a class is a specific implementation body, and an interface defines the specifications that a batch of classes need to comply with, the interface does not care about the internal data of these classes, or the Implementation Details of methods in these classes, it only specifies certain methods that must be provided in these classes. (Similar to abstract classes)
2. Basic Syntax of Interface Definition
[Modifier] [abstract] interface name [extends parent interface 1, 2...] (Multi-Inheritance){
0... N constant (public static final)
0... N abstract)
}
The content in [] indicates the option, which can be written or not written. The attributes in the interface are constants. Even if the public static final modifier is not added during definition, the system automatically adds the modifier; all methods in the interface are abstract methods. Even if the public abstract modifier is not added during definition, the system automatically adds them.
3. Use Interfaces
A class can implement one or more interfaces. The Implemented interfaces use the implements keyword. A class in java can inherit only one parent class, which is not flexible enough. It can be supplemented by implementing multiple interfaces.
The syntax for inheriting the parent class implementation interface is:
[Modifier] class name extends parent class implements interface 1, interface 2 ...{
The class part // If the abstract class is inherited, the inherited abstract method must be implemented; the abstract method in the interface must be implemented
}
Note: To Inherit the parent class, the parent class must be inherited before the interface is implemented, that is, the extends keyword must be before the implements keyword.
Note: When naming an interface, we often start with I to distinguish between common classes. For example, IPlayGame
The following is an example of the abstract class. We have previously defined an abstract class Telephone and a subclass Phone. Here we create an IPlayGame interface, then, slightly modify the two classes defined in the original definition. The Code is as follows:
1 public interface IPlayGame {2 public void paly (); // The abstract keyword can be omitted. The system automatically adds 3 public String name = "game name "; // The static final keyword can be omitted. The system automatically adds 4}
1 public class Phone extends Telephone implements IPlayGame {2 3 public void call () {// The subclass that inherits the abstract class must override the abstract method 4 // TODO Auto-generated method stub 5 System. out. println ("I have rewritten the abstract class method"); 6} 7 8 @ Override 9 public void paly () {10 // TODO Auto-generated method stub11 System. out. println ("I have rewritten the interface method"); 12} 13 14}
1 public class train {2 3 4 public static void main (String [] args) {5 // TODO Auto-generated method stub 6 IPlayGame I = new Phone (); // use an interface reference to point to the subclass object 7 I. paly (); // method of calling the interface 8 System. out. println (I. name); // constant of the output interface 9 10 11 12} 13}
Running result:
4. Use APIs with anonymous internal classes
APIs are often used with anonymous internal classes. An anonymous internal class is an internal class without a name. It is mostly used to focus on the implementation rather than the name of the implementation class.
Syntax format:
1 Interface I = new interface () {2 Public void method {3 System. out. println ("using anonymous internal classes to implement interface 1"); 4} 5}; 6 I. method ();
There is another way of writing: (directly write the call of the method at the end of the anonymous internal class)
1 Interface I = new interface () {2 Public void method {3 System. out. println ("using anonymous internal classes to implement Interface 1"); 4} 5}. Method ();Iv. Differences between abstract classes and interfaces
In the process of multi-state learning, we realized that abstract classes and interfaces are the key parts to implement java polymorphism. Both of them contain abstract methods. They only focus on the declaration of methods rather than the specific implementation of methods, what is the difference between the two ?? What should we choose when writing a java program?
Reference blog: http://www.cnblogs.com/felixzh/p/5938544.html
(1) syntax differences
1. A class can inherit only one abstract class, but a class can implement multiple interfaces.
2. the member variables in the abstract class can be of various types, while the member variables in the interface can only be of the public static final type, and the initial values must be given, so the implementation class cannot be redefined, the value cannot be changed. The variables in the abstract class are of friendly type by default. The values can be redefined in the subclass or assigned again.
3. abstract classes can contain non-abstract methods, and interfaces cannot contain non-abstract methods.
4. abstract keywords can be omitted in the interface, but abstract classes cannot.
5. The interface cannot contain static code blocks and static methods. abstract classes can have static code blocks and static methods;
(2) differences at the design level
1) An abstract class is an abstraction of a thing, that is, class abstraction, while an interface is an abstraction of behavior. Abstract classes abstract the entire class, including attributes and behaviors, but interfaces abstract the local (behavior) of the class. For example, airplanes and birds are different things, but they all share the same thing, that is, they all fly. During the design, the aircraft can be designed as an Airplane class, and the Bird can be designed as a Bird class. However, the flight feature cannot be designed as a class, therefore, it is only a behavior feature and is not an abstract description of a class of things. In this case, you can design the flight as an interface Fly, including the method fly (). Then Airplane and Bird implement the Fly interface according to their own needs. Then we can directly inherit Airplane from different types of aircraft, such as fighter planes and civil aircraft. It is similar to birds. Different types of birds can directly inherit the Bird class. It can be seen from this that inheritance is a "not" relationship, while interface implementation is "not. If a class inherits an abstract class, the subclass must be the class of the abstract class, and the interface implementation has no or no relationship, for example, whether a bird can fly (or whether it is capable of flying), this interface can be implemented if it can fly. If it cannot fly, this interface will not be implemented.
2) the design level is different. abstract classes are the parent classes of many sub-classes. They are a template-based design. The interface is a behavior specification, and it is a radiation design. What is template design? In the simplest example, you have used templates in the ppt. If template A is used to design the public parts of ppt B, ppt C, ppt B, and ppt C, it is template, if they need to be changed in the public part, you only need to modify template A, and do not need to modify the ppt B and C. Radiation design, for example, a certain alarm is installed on an elevator. Once an alarm is updated, it must be all updated. That is to say, to add a new method to an abstract class, you can directly add the specific implementation to the abstract class, And the subclass can not be changed. The interface cannot be used. If the interface is changed, all classes that implement this interface must be modified accordingly.
Next, let's take a look at the most widely circulated online example: the door and alarm example: the door has two actions: open () and close, in this case, we can define this abstract concept through abstract classes and interfaces:
1 abstract class Door {2 public abstract void open();3 public abstract void close();4 }
Or:
1 interface Door {2 public abstract void open();3 public abstract void close();4 }
But now, if we need the function of alarm (), how can we implement it? The following two ideas are provided:
1) Put these three functions in the abstract class, but in this way, all subclasses inherited from this abstract class have the alarm function, but some do not necessarily have the alarm function;
2) place these three functions in the interface. To use the alarm function, you need to implement open () and close () in this interface (), maybe this class does not have the open () and close () functions at all, such as fire alarms.
From this we can see that Door's open (), close (), and alarm () are essentially two different categories of behavior, open () and close () it belongs to the inherent behavior characteristics of the door, while alarm () is an extended additional behavior. So the best solution isThe alarm is designed as an interface, including alarm () behavior. The Door is designed as an abstract class, including open and close actions. Design an Alarm Door to inherit the Door class and implement the Alarm interface.
1 interface Alram { 2 void alarm(); 3 } 4 5 abstract class Door { 6 void open(); 7 void close(); 8 } 9 10 class AlarmDoor extends Door implements Alarm {11 void oepn() {12 //....13 }14 void close() {15 //....16 }17 void alarm() {18 //....19 }20 }
After writing this blog post, the three main features of java are the core and foundation of object-oriented programming. The concept understanding here is of great help to actual programming, and the content may be too tedious, if you have any questions about the content, please leave a message below or send a private email. Thank you !!