Java Learning Series (4) Java object-oriented modifier, encapsulation, inheritance, and Polymorphism

Source: Internet
Author: User

Today, we have a lot of content. Let's go straight to the question. Classes and object definitions a class is a reflection of entities in the real or thinking world in a computer, which encapsulates data and operations on such data. The object is a variable of the class type and exists in the heap memory. A class is the abstraction of an object, and an object is a specific instance of a class. Classes are abstract and do not occupy memory, while objects are specific and occupy storage space. Define a class syntax format [modifier] class name {// can have attributes, methods, constructor, initialization block, enumeration class, internal class, etc ..} Note: The class modifier can be omitted (it must be in the same package, as described below), public, final (cannot be inherited), abstract (you cannot create an instance, but added a function that can contain abstract methods ). The class name must be a combination of multiple meaningful words (uppercase letters. Note that there is no sequence between modifiers. Syntax format of attribute definition: [modifier] Type field name [= default value]; [modifier] -- can be omitted. It can also be public | protected | private, static, final. Type -- cannot be omitted. Can be basic type, array, any class (JDK class and custom class), interface, enumeration. Field name -- cannot be omitted. Must be multiple meaningful words (the first letter is in lowercase ). [= Default value] -- can be omitted. Syntax format of method definition: [modifier] Return Value Type method name (multiple parameter declarations) {// 0 ~ N executable statements // if there is a return value type declaration in the method signature, the method must contain a [valid] return Statement} [modifier] -- can be omitted. It can also be public | protected | private, static, final | abstract. Return Value Type -- cannot be omitted. --- During compilation, the system deems that the return in if may not be executed (not valid ). Method Name -- cannot be omitted. -- It is generally a verb. The first letter is in lower case and the last letter is in upper case. Parameter Declaration-each parameter must meet the format of "type" and "variable. Note: There is only one parameter transfer mechanism for Java Methods: value transfer. Note: There is a variable number of parameters in Java, such as public void info (int... nums): nums here is an int type array. (Parameters are not required during the call.) each method can have at most one variable parameter (essentially an array ). Parameters with variable numbers must be placed at the end of the parameter. Syntax format defined by the constructor (which is provided by the system by default and can be reloaded): [modifier] constructor name (0 ~ N parameter declarations) {// 0 ~ N executable statements} [modifier] -- can be omitted. It can also be public | protected | private. Constructor name -- it cannot be omitted and must be the same as the class name. The constructor can be considered as a special method for generating objects (through the constructor to initialize class instances ). Note that the assignment in the previous chapter is an executable statement and should be placed in the method or constructor. The initialization block (with no name) Syntax: The [modifier] {// executable statement} modifier can only appear static. Static indicates that it is a class initialization block. The code of the Instance initialization block (without modifier) is "implicitly" executed before each constructor call. Rule: code that is located before the constructor and does not need to pass parameters can be extracted to the initialization block, so it has a higher priority than the constructor, during compilation, the code of the Instance initialization block will be extracted to the front of the constructor ". Class (static) initialization: When a class is loaded, it is implicitly executed after class initialization. A jvm only initializes a class once. When the program uses this class for the first time, it will initialize the class. In the following situations, the class will be initialized. A. The static field or static method is accessed. B. initialize the subclass of this class. Because Java initializes a class, it always starts initialization from the top parent class. C. use reflection to Class. forName (Class Name string) D. if this class is used as the main class (the main method is available, and the program is indeed executed from the main method) E. use this class to create objects. Packing and unpacking: automatic packing: the value of the basic type, which can be automatically used as its packaging class instance. It can be used automatically as an object or as an object input method. Automatic unpacking: When necessary, the program will automatically split the package instance into basic type values. Local variables can be local variables in the method, parameters, and local variables in the code block (only valid in curly brackets ). The local variables in the method belong to the method. The modifier can only be final and must be initialized. Local variables are neither instance nor class, so local variables cannot be modified using static. The member variable system initializes the variable. We usually write A a = new A (). In fact, what we do is to create an object A (stored in the heap) and let the referenced variable a point to object. When we print an object, it actually prints the return value of the toString () method of the object. Modifier: static: A member (attribute or method) that has a static (Class Identifier) modifier belongs to the class itself (called a class member ), the opposite is the instance of the class (we call it an instance member ). Remember never use an object to call static methods and properties. If so, you must translate the object into a class (when the program uses an instance to invoke class variables, because the class variable itself does not belong to the instance, the underlying layer is delegated to access through the class, and Members with static modification cannot access non-static members ). This (available in any non-static modifier method or constructor) has two keywords: 1. this reference: When this is in a method, this indicates the object that calls this method. When this is in the constructor, this indicates that the constructor is initializing the object. 2. this call. --- It can only appear in the first line of the constructor. Final modifier: The final modified member variable (filed), which must be initialized by the programmer (can only be assigned once and cannot be changed ). --- The initial value can only be specified in the definition, initialization block, or constructor. If final modifies a class variable (a member modified by static), the initial value can only be specified in the definition or class (static) initialization block. Final-modified local variables: they cannot be re-assigned. JVM caches all used objects. The final modified variable will be replaced by the execution macro. If the final modified variable can be determined during compilation, the variable will not exist. The final modification method cannot be overwritten. Benefit: the method of the parent class is forbidden to be overwritten to prevent the parent class from being damaged. The final class cannot have subclasses, Which is safer. Method Overload: The method parameters of the same method name in the same type are different, and are irrelevant to the return value type and modifier static. Override: overwrite is also called overwrite: When a subclass inherits from its parent class to obtain a method that does not really meet the requirements of the subclass, The subclass can Override the method of the parent class. The method name and parameter list are the same. The method access permission of subclass rewriting must be greater or equal than the access permission of the parent method; the Return Value Type of the override method must be smaller or equal than the return value type of the parent class method. The declared exception of the override method must be smaller or equal than the exception thrown by the parent class declaration. Note: We often add the @ Override annotation to the method. Its function is to let the compiler execute the check and require the class to Override the method of the parent class. Package and static import: the package actually serves as a namespace. Java requires the complete Class Name of a class = package name + class name. The package name must be in lowercase. To put a class into the package, you must use the package in the source code of the class to declare the package. The generated class file must be placed under the corresponding file structure. The normal import is to omit the package, while the import static imports static members under the specified class (class names can be omitted during the call ). Object-oriented encapsulation: encapsulation is to hide attributes, methods, and constructors that do not want to be operated by the outside world. Provides methods called by others. Encapsulation purpose: simplify programming and ensure Object Integrity. We have to talk about encapsulation: access permission modifier: private -- access permission of the current class. No access modifier-package access permission. Protected -- subclass access permission. Public -- public access permission. The access permission ranges from small to large: private --> NO (default) access modifier --> protected --> public. If the attribute is assigned directly, the data integrity of the class is easily damaged. This is generally not recommended. Object-oriented Inheritance (extends): the relationship between classes from general to special ("is a"). For example, Apple is a kind of fruit, then Apple can inherit from the fruit, and the Child class inherits the parent class (the object of the parent class is implicitly obtained) to obtain the attributes and methods. However, this will increase the Coupling Degree (Child classes will also be changed once the parent class attributes or methods have changed). Therefore, it is generally recommended to use combinations, so inheritance can be avoided as much as possible. In addition, a combination is a "has a" relationship that can explicitly obtain the object of the contained class. The combination relationship is determined at runtime, while the inheritance relationship is determined at compilation. The combination is a loose coupling between the combination class and the included class, inheritance is a tightly coupled relationship between the parent class and the Child class. Super Keyword: super can be used in two ways: super limitation: Methods and fields that force access to the parent class. -- If the subclass defines a field with the same name as the parent class, it will not be overwritten. Super call: Used to explicitly call the constructor of the parent class. Rule: the constructor of the subclass [always] First calls the constructor of the parent class [once]. Note: Both super and this must appear in the first line of the constructor, it cannot be repeated. If this is called, The subclass constructor first finds the constructor that is overloaded in the subclass corresponding to this call. Object-oriented polymorphism (Ploymorphism): variables of the same type exhibit multiple behavioral characteristics when executing the same method. Example 1: [java] view plaincopy <pre name = "code" class = "java">/** @ Author: lhy * @ Description: fruit class, used as the parent class; apple class inherits from Fruit **/class Fruit {public void info () {System. out. println ("the info method of the parent class is called! ") ;}} Class Apple extends Fruit {public void info () {System. out. println (" before the info method of the subclass is called! "); Super.info (); System. out. println (" after the info method of the subclass is called! ") ;}} Public class Test {public static void main (String [] args) {Fruit f1 = new Apple (); Fruit f2 = new Fruit (); f1.info (); f2.info () ;}}</pre> <br> run the command. You can see that the variable f1 of the same type (Fruit) is used, different behavioral characteristics are displayed. In addition, subclass instances can be used as parent class objects. Polymorphism increases the flexibility of the Java language and is closely linked to the design pattern (will be discussed later ). Let's look at another one:

<Pre name = "code" class = "java"> class Fruit {protected int I = 1000; public void test () {System. out. println ("the test method of the parent class is called! ") ;}} Class Apple extends Fruit {protected int I = 10; public void test () {System. out. println (" the test method of the subclass is called! ") ;}} Public class Test {public static void main (String [] args) {Fruit f1 = new Apple (); // when a variable is referenced, it always presents its runtime features. F1.test (); System. out. println (f1. I);/* between reference types, only two types with inheritance relationships can be converted; otherwise, an error will be reported during compilation! The forced type conversion operator is (type) */System. out. println (Apple) f1). I) ;}</pre> <br>

 

Note: There are two types of referenced variables in Java, the compile-time type (determined by the declared type ), runtime type (determined by the Type actually assigned to the variable ). In the compilation phase: the compiler does not know the type of the object actually referenced by the referenced variable. Instanceof Keyword: used to determine whether the object referenced by the preceding variable is of the subsequent type. Note: The type of the first operand of instanceof is either the same as that of the next class or has a parent-child relationship with the next class. Otherwise, a compilation error occurs. Conclusion: There are many contents, So we plan to discuss them in Chapter 2-3. It is important to start talking about interfaces, abstract classes, internal classes, and enumeration classes tomorrow. It will often be seen in future design patterns and will be frequently used in Java web development in the future, the web framework itself is not difficult, but it is difficult to configure some xml files. However, these configurations generally do not need to be deliberately recorded. Therefore, it is necessary to learn the basics of Java in the future of Java web and Android.

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.