JAVA class and Object

Source: Internet
Author: User

1. Class Definition
Abstract concepts Describing Objects. Objects with similar properties and behaviors can be classified into a class.
In software, a class is a template that defines the states (variables) and actions (methods) of all objects of a specific type ). A class is a template for creating objects, and an object is a class instance.
 
Declaration Form
[Public] [abstract | final] class name

[Extends parent class name]

[Implements Interface Name List]

{

Data member declaration and initialization;

Method member declaration and method body;

}

Keywords
Declare class: indicates that it is declared as a class.
Extends: If the declared class is derived from a parent class, the name of the parent class should be written after extends.
Required implements: If the declared class needs to implement some interfaces, the interface name should be written after implements
Class Modifier
There can be multiple, used to limit the usage of Classes
Public: indicates that this class is a public class.
Abstract: specifies this class as an abstract class.
Final: specifies that this class is the final class.
Class declaration body
Token data member declaration and initialization
-There can be multiple
Token method member declaration and method body
-There can be multiple
Data Member
Status indicates the status of the Java class
Declare that the data member must give the variable name and its type, and you can also specify other features
The member variable name in a class is unique.
The worker data member type can be any data type in Java (basic type, class, interface, array)
Method Member
Define class behavior
-What an object can do
-Information we can obtain from an object
There can be either none or multiple;
Instances are divided into instance methods and class methods (static methods)
 
Access Control for Class Members

Public
Members can be accessed by all classes.
Protected
Members can only be accessed by classes, derived classes, or classes under the same package.
Private
Other members are not allowed to access any class except the class itself.
Default
The member can only be accessed by the class itself or the class under the same package.
 
2. Special member of the class

Constructor
The struct constructor has the same name and class name, and no return value (even void is not allowed ).
The struct constructor is mainly used to define the initialization status for the object of the class.
You cannot directly call the constructor. You must use the new keyword to automatically call the constructor to create a class instance.
All classes in Java require a constructor. If no constructor is defined, the Java compiler will provide us with a default constructor, that is, a constructor without parameters.
 

Static Data Member
Modify static members with the static keyword, such:
Keep Class Person {
Staticint name;

Public static void getName (){......};

}

Static methods and static variables belong to a class instead of class objects. No matter how many objects there are, static members only have one copy in the memory, all objects share the same static member.
The reference of static methods and static variables can be directly referenced by class names without class instantiation. For example: Person. name; Person. getName ();
You cannot call non-static methods or reference non-static member variables in static methods. Otherwise, you can.
 
Final data member
Structured final data members are similar to const data in C ++ and macro definitions in C.
Once initialized, the final data member cannot be changed. The value of final data cannot be changed for the basic type, but for the object variable, its reference cannot be changed, however, the content in the object to which the referenced variable points can be changed.
 
Final method Member
A derived class can only inherit the final method from the parent class, but cannot overwrite the final method.
Declare a method can be declared as final when the functions provided by a method meet the requirements and do not need to be extended or do not want to be overwritten by the quilt class.
 

Abstract methods and abstract classes

A method without a method body in a class is an abstract method.
Classes that contain abstract methods are abstract classes.
If a subclass does not implement all abstract methods in the abstract base class, the subclass also becomes an abstract class.
We can declare a class without any abstract method as abstract to avoid generating any objects from this class.
Constructor, static, private, and final methods cannot be declared as abstract methods.

 

3. object-oriented concepts

Design a window

Pipeline process-oriented:
Defines the size, position, color, background, and other properties of a window in a struct. The function of window operations has no relationship with the definition of the window itself, such as HideWindow, all functions of MoveWindow need to accept a window parameter that represents the operation. This can be understood as the relationship between the predicates and objects.

Region object-oriented:
When defining a window, you must specify the properties of the window, such as size, position, color, and so on. You must also specify the actions that the window may have, such as hiding and moving. When these functions are called, they are used to hide a window and move the window in a format. They can be understood as the relationship between the subject and the predicate.

 

Three features of object-oriented

Encapsulation
Volume encapsulation organizes processes and data. Data access can only be implemented through defined methods.
The intent of the consumer encapsulation is to separate the object user from the designer. the user does not need to know the details of the behavior implementation, but only needs to use the message provided by the designer to access the object.
 
Inheritance
The new category class can obtain the attributes and behaviors of an existing class (called a superclass, base class, or parent class). The new class is a derived class (also called a subclass) of an existing class ).
Inheritance can increase code reusability and add functions based on the features of the parent class.

 

Polymorphism
The producer sends a message to an object so that the object determines the action to respond. It can be understood as a vertical overload and vertical coverage.
NLP makes the language flexible, abstract, behavior sharing, and code sharing advantages, and solves the problem of the same name in the application method.
 
Overload)
BaseClass base = newBaseClass ();

Int temp = 1;

Base. fun (); // without Parameters

Base. fun (temp); // parameters with int type

 

Override)
DerivedC derived = newDerivedC (); // Derived inherits from BaseClass.
BaseClassbase = derived;
Base. play (); // execute the play () defined in DerivedC ().

 

Class Declaration

Public class Window {
Int size;

Private int position [2];

Protected int color;

Public void setSize (intnewSize ){

Size = newSize;

}

Protected void setPosition (int x, int y ){

Position [0] = x;

Position [1] = y;

}

Private void setColor (intnewcolor ){

Color = newColor;

}

......

}
 
Class instance
Class does not execute any function, but is completed by the object instance created by the class.
Object Creation
Registrant Person per = new Person ();
Registrant Person per; per = new Person ();
Every object in the queue can be used only after the memory space is allocated by the keyword new.
Call of data members
Statement per. name = "Li ";
Counter per. tell ();
 

4. All objects are referenced.

C ++ has two ways to manipulate objects.
Identifier 1. Identify the object directly with an identifier;
Person per = Person ();

Per. say ();

Identifier 2. Indirectly identifies an object using a pointer.
Person * per = new Person ();

Per-> say ();

Java only has one way to manipulate objects
All object IDs of objects are referenced by objects.
 

Reference VS pointer

References are similar to pointers, but references do not have the semantics of pointers.
Pointers support arithmetic operations and can be moved freely before and after the operation. This also causes many insecure pointers.
A reference can only reference a new object through a value assignment. arithmetic operations are not allowed. The reference can be understood as a safer pointer.
 
The so-called reference data type actually transfers the right to use the heap memory. You can define multiple stack memory reference operations for a heap memory space at the same time.
Public class Person {
Optional String name;
Optional int age;
Using public void tell (){
-System. out. println ("name:" + name + "age:" + age );
Token}
 
Public class Example {
Public static void main (String args []) {

Person per1 = null;

Person per2 = null;

 

Per1 = new Person ();

Per2 = new Person ();

 

Per1.name = "James ";

Per1.age = 30;

Per2.name = "Li Si ";

Per2.age = 33;

Per2 = per1;

Per2.age = 25;

Per1.tell (); // What is output? Name: Zhang San age: 25

}

}
 
Object Memory Allocation
Objects are stored in the stack memory, and data members are stored in the heap memory. Each object has its own copy of data in the memory.
The method member is saved in the code area and only one copy is available in the memory. All objects in the same class share the same program code.
Thinking: How to differentiate data of different objects when objects share the same program code?
This variable represents the object itself. Each method member has an internal this reference variable pointing to the current object. Every time an instance method is called, this variable is set to a specific class object that references the instance method. The Java compiler will pass this variable to the instance method. The method code can then be associated with the specific data of the object represented by this.
 
5. Object replication: Deep replication and light Replication
1. When do I need object replication?
Status Replication
Assignment value displayed by dimensions
-Copy the status of an object to another object.
Consumer object initialization
-Use the status of an existing object to determine the status of a new object.
Make a copy
Callback object as a method parameter
-Call an object by value.
Response object as return value
-Copy a partial object in the method and return it
 
JAVA object transfer
In Java, the effect of passing an object as a parameter is always passed by reference. Only the replication of object reference does not occur.
Secondary advantage: high efficiency (no need to make copies)
Disadvantages: unsafe (method calls have side effects)
If you use final to modify object parameters, you still cannot correct the preceding disadvantages. This ensures that object reference has no side effects and the object instance may be changed.
Solution: copy the object in the method to pass the object by value.
Benefits: Security
Disadvantages of compaction: inefficiency (more manual programming is required to make copies)
 
2. Differences between deep replication and light Replication
Composite object: The object also contains references to other objects.
Deep replication makes sense only for composite objects, and has the same effect for common objects.
For composite objects, what is the difference between two-step replication:
Shallow copy: only copies the root object of the composite object-only copies the object reference and does not copy the object instance.
Deep copy: Copies the entire structure of the composite object-deep copy recursive copy of each sub-object in the composite object
 
Copy instances in depth-implement the Cloneable Interface
The Object class is the base class of all classes, and all classes are inherited from the Object class.
The clone () method defined in the Object class adopts the shortest replication policy.
Public class Teacher {
String name;

Int age;

Public Teacher (String name, int age ){

This. name = name;

This. age = age;

}

}
 
Public class student implements Cloneable {
String name;

Teacher teacher;

Public student (String name, Teacher teacher ){

This. name = name;

This. teacher = teacher;

}

Public Object clone (){

Student stu = null;

Try {

Stu = (Student) super. clone ();

} Catch (CloneNotSupportedException e ){

System. out. println (e. toString ());

}

// Stu. teacher = (Teacher) teacher. clone ();

Return stu;

}

}
 
Teacher teacher = new Teacher ("Zhang San", 30 );

Student stu1 = new Student ("James", teacher );

Student stu2 = (Student) stu1.clone ();

Stu2.teacher. name = "Li Si ";

Stu2.teacher. age = 32;

System. out. println (stu1.name + "Instructor information:" + stu1.teacher. name + "" + stu1.teacher. age );

// What is the output result?

Miss James: Li Si 32

 

Deep Replication

Modify the Teacher Class (parent class) and redefine the clone method for the Teacher class.
Public class Teacher inplementsCloneable {
String name;

Int age;

Public Teacher (String name, int age ){

This. name = name;

This. age = age;

}

Public Object clone (){

Teacher teacher = null;

Try {

Teacher = (Teacher) super. clone ();

} Catch (CloneNotSupportedException e ){

System. out. println (e. toString ());

}

// This. name = new String (teacher. name );

Return teacher;

}

}
Share:

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.