Object-oriented encapsulation, abstraction, inheritance, and Polymorphism in Java

Source: Internet
Author: User

This article introduces the object-oriented encapsulation, abstraction, inheritance, and polymorphism features in Java. If you need them, please refer to them.

Object-oriented has four main features: encapsulation, abstraction, inheritance, and polymorphism. Definitions:
Encapsulation: In object-oriented languages, encapsulation features are embodied by classes. We define a class of entities in real life as classes, this includes attributes and behaviors (in Java, it is a method), just like humans, which can have attributes such as name, sex, age, and eat () and sleep, we implement certain functions and operational attributes in line, which is an object-oriented encapsulation feature;
Abstract: Abstraction abstracts the common characteristics of a class of entities and encapsulates them in an abstract class. Therefore, abstraction is embodied in object-oriented languages by abstract classes. For example, a bird is an abstract object. Because an abstract object is not a real object, its attributes cannot completely describe an object, so the abstract class cannot be instantiated;
Inheritance: inheritance is like the parent-child relationship in our real life. A son can inherit some features of his father. In object-oriented languages, a class can inherit some features of another class, so that code can be reused. In fact, inheritance reflects the is-a relationship, and the parent class is essentially a class object;
Polymorphism: Polymorphism means that different sub-class objects are referenced to the parent class object to exhibit different behaviors. polymorphism can provide better scalability and code reuse for the program.

1. Date t = new Date (); there are two parts. new Date () constructs a Date-type object (Java objects are stored in the heap ),
References to this object are stored in object variable t. Java object variables are different from C ++ references.
The application cannot be assigned a value. Java object variables can be considered as object pointers of C ++. The null reference in Java corresponds to the NULL pointer in C ++.
 
2. Static methods are methods that cannot perform operations on objects, so they cannot access domains in static methods.
Use static methods in two cases:
1). A method does not need to access the object state, and all the required parameters are provided by the form parameters.
2) A method only needs the static domain of the callback class.


3. Do not return a reference to a variable object in the getXX method. For example:
Public Date getDate (){
Return date;
}
Private Date date;
Cause: the encapsulation is broken. If A variable such as newDate = A. getDate () is made, the private domain of the Date class can be modified in newDate.
To return a reference, clone: return (Date) date. clone () first ().


Static domain and static method
1. Static domains, also known as class variables, are shared by all instances;
2. The static method is a method that cannot perform operations on objects, so it cannot access the instance domain in the static method, but it can be a static domain in the hosts class.

Why do the NumberFormat class not use the constructor to perform these operations? Two reasons:
1). the constructor cannot be named. The constructor name must be the same as the class name. However, the expected currency instance and percentage instance use different names;
2) When the constructor is used, the constructed object type cannot be changed. The Factory method returns a DecimalFormat Class Object (subclass of NumberFormat ).

Both static variables, static methods, and static blocks are executed during class loading, while initialization blocks are called during class instantiation.
When a class is running, JVM will perform the following tasks: 1. class loading 2. Link 3. Initialization 4. instantiation; in the initialization phase, static variables are initialized and static methods are executed.


Method Parameters)
A method cannot modify a parameter of the basic data type;
A method can change the state of an object parameter (the parameter is an object variable );
A method cannot allow object parameters to reference a new object.
Note: Java overload (the return type is not part of the method signature ).

 


Polymorphism: an object variable can reference multiple types of phenomena.
Dynamic binding: when running, you can automatically select the method to call.
1. variables (regardless of static variables or instance variables) are static bindings, and static bindings correspond to declared object variable types. (During compilation)
2. For methods, private, static, and final methods are static bindings, others are dynamic bindings, and the corresponding object type is dynamically bound. (Runtime)
That is, Father f = new Son (); f. field and f. static_method () calls the super class, that is, the Father member. To access the subclass variable, you can use the getX () and setX () methods.
In other forms, the Child class is called.
Note: compilation fails when the superclass method is private.
3. When overwriting a method, the subclass method cannot be lower than the superclass method's visibility.

 


Abstract class
1. Classes containing one or more abstract methods must be declared as abstract;
2. In addition to abstract methods, abstract classes can also contain specific data and methods;
3. When an abstract class is extended, if only some abstract methods of the super class are defined, the subclass should also be an abstract class. If all the methods are defined, the subclass is not abstract.
4. the abstract class cannot be instantiated. Therefore, object variables of abstract classes cannot reference objects of abstract subclasses.
Note: Abstract [] a = new Abstract []; // declares an array of Abstract objects instead of Instantiation.


Important Object Methods
1. equals Method
In an Object, equals compares references (that is, the memory address), which is equal to =; therefore, in a class that does not overwrite the equals method, equals compares references;
Classes that cover the equals method are determined based on the specific implementation. The content is generally compared, for example, the equals method of the String class. = Is always the address.
For more details, see.
 
2. hashCode
Hash code is an integer exported from an object, and it is irregular. Different object hash codes are generally different. If you redefine equals
You must re-define the hashcode method so that you can insert objects to the hash list. The Equals and hashCode definitions must be consistent: If
X. equals (y) returns true, so x. hashCode () must have the same value as y. hashCode.

 
Interface:
1. All methods in the interface automatically have the public attribute. The interface cannot contain instance domains (except for final constants, and the constant attribute is automatically public static final ),
It cannot be implemented in the interface.
2. Like inheritance, you must provide access permissions not lower than the previous layer (interface or superclass) when implementing interfaces. Therefore, the method must be declared as public.
3. Like an abstract class, an interface cannot be instantiated. You can declare an interface variable but must reference a class object that implements an interface.
 
Interfaces and abstract classes: each class can only expand one (abstract) class, but can implement multiple interfaces (Multi-inheritance)
Clone
In the Object class, clone is the protected method, which is visible to this package and all subclasses (including the outer package. However, I tested it by calling the clone method with a self-compiled class,
The CloneNotSupportedException exception is thrown during runtime, And the clone method is a local method. Why can't I call it directly ??? The reason is as follows:
You must implement the Cloneable interface and do not provide the clone method.

Sample Code:

The Code is as follows: Copy code
Public class Son extends Father implements Cloneable {
Public static void main (String [] args) throws Exception {
Son s = new Son ();
S. A (); // call A () of the Father class, and the output string ""
Son s1 = (Son) s. clone ();
S1.A ();
}
}

Output result:
 
Shortest: the default clone operation. It does not clone the internal objects contained in the objects. However, if the objects in the instance domain are immutable or basic types
(The clone method does not need to be redefined, but we recommend that you redefine and call the clone: super. clone () of the Object ());
Deep copy: Based on the shortest copy, the internal objects in the object are cloned (the clone method must be redefined ).
 
To clone a class, you must meet the following requirements:
First, it must implement the Cloneable interface; otherwise, a CloneNotSupportedException exception will be thrown;
Second, it must provide a public clone method, that is, rewrite Object. clone () method, otherwise the compilation fails.
In addition, for classes with variable domains, You need to copy these variable domains in the clone method (deep copy ).

Note: The Object class itself does not implement the interface Cloneable. Therefore, calling the clone method on the Object whose class is Object will throw an exception during runtime.
The Cloneable interface does not define any method. It is only used as a tag and should be cloned on the surface.
 
Internal class:
1. Member internal class
Description: it is a member of an external class and is in parallel with the attributes and methods of the external class. You can instantiate internal class objects in external class methods to access internal class methods.
The object of the member's internal class has an implicit reference, which references the external class object that instantiates the internal object. With this pointer, you can access any domain and
Method. However, internal classes cannot define static members (except static internal classes ).
Special Syntax:
External class reference expression OuterClass. this;
Internal object constructor: outerObject. new InnerClass (parameters );
Note: You can use OuterClass. InnerClass to reference internal classes outside the scope of external classes.
 
2. Anonymous internal class
Syntax format:

The Code is as follows: Copy code
New SuperType (construction parameters)
{
Inner class methods and data
}

If SuperType is an interface, the internal class must implement this interface. If SuperType is a class, the internal class must expand it.
 
3. static internal class: the internal class is used only for hiding. You can declare the internal class as static and cancel the reference of the external class. It can be viewed as a static member of an external class.
 
4. Local internal class:
Define a local class in a method. Public or private access specifiers cannot be used for declaration. Its scope is limited to the block that declares this local class.
In addition to this method, no other method knows the existence of a local internal class, but you can use an external class object to call this method to indirectly access the internal class. In
The internal class can access the local variables of the internal class (that is, the variables in the method), but the variables must be final.

The following is an example to illustrate the magic of polymorphism.

There is A parent class:

Java code

The Code is as follows: Copy code

Public class {

Public void methodA (){

System. out. println ("This is Parent of .");

}

}

Public class {

Public void methodA (){

System. out. println ("This is Parent of .");

}

}

Parent Class A has the following three subclasses:

The Code is as follows: Copy code

Java code
Public class B1 {

Public void methodA (){

System. out. println ("This is Children of B1 .");

}

}

Public class B2 {

Public void methodA (){

System. out. println ("This is Children of B2 .");

}

}

Public class B3 {

}

Public class B1 {

Public void methodA (){

System. out. println ("This is Children of B1 .");

}

}

Public class B2 {

Public void methodA (){

System. out. println ("This is Children of B2 .");

}

}

Public class B3 {

}

Subclass B above! And B2 both override the method methodA of the parent class A, while B3 does not. Next, let's take a look at the actual call statement.

The Code is as follows: Copy code

1. A a1 = new ();

2. A a2 = new B1 ();

3. A a3 = new B2 ();

4. A a4 = new B3 ();

5. a1.methodA ();

6. a2.methodA ();

7. a3.methodA ();

8. a4.methodA ();

The running result of the preceding statement is as follows:

This is Parent of.

This is Children of B1.

This is Children of B2.

This is Parent of.

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.