[Java Learning note]-java objects and classes

Source: Internet
Author: User
Tags modifiers

Java is a fully object-oriented, high-level language, and its basic operations are essentially for the corresponding objects and classes. Object-oriented programs are made up of objects, each containing a specific part of the functionality exposed to the user and a hidden implementation part. Corresponding to the object-oriented language, there is also a process-oriented language, such as the C language. The object-oriented language is developed on the basis of the process-oriented language. Object-oriented (OOP, all called Object-oriented-programer, hereinafter referred to as OOP) is the advantage of a process-oriented language in that many problem solving methods are encapsulated in objects, sometimes only to create such objects to solve our problems, Without having to worry about its specific implementation details, this is obviously a great convenience for development.

In the process-oriented language, the famous Hungarian mathematician computer von Neumann has a Classic view: algorithm + data structure = program. In this programming language, the programmer must first determine how to manipulate the data, that is, to solve the problem of the specific process of implementing the algorithm, and then consider how to organize the data. OOP, however, swapped the order, putting the data first, and then considering the algorithm.

Here are some important concepts in the Java language: Class, Object, method

1. Class

1.1 What is a class

Class, which is the template and blueprint for constructing the object. Popularly speaking, the class is the human brain corresponding to many individuals in the real life of the characteristics of the generality of the abstract out in the field of consciousness represents a concept of the individual. For example, people are not the concept of nature, "man" is just our abstract description of our human beings, it represents an individual, it can also represent our entire human population. When we speak of human beings, we do not refer to a specific person, but to a generalization.

1.2 How to declare a class

Declaring a custom class in Java is a simple format: Class classname{}.

Here comes a word class, which is the Java keyword, which must be written when defining a class, and ClassName is a name. It is a valid Java identifier. And then a pair of "{}", delimiters, representing the body of the class. Of course, the modifier such as, the permission modifier public, and so on that can be modified are omitted here.

What are the benefits of class 1.3?

I think the introduction of "class" is a great improvement in programming language. Because, a class is like a factory that can quickly produce objects. The process of constructing an object from a class is what we call an instance of creating a class. Class has three main features: encapsulation, inheritance, polymorphism. These three features make up the benefits of using classes. The specific examples are explained later.

2. Object

2.1 What is an object

object, is the concrete thing in reality. For example, President Barack Obama. The object in OOP is the real problem solving. In the process-oriented language, our problems are all given to programmers, often programmers to compile specific programs to solve such problems. The solution to the problem in OOP is encapsulated in the object and is written in the body of the class. Programmers sometimes do not need to write a lot of code to solve the problem at hand, only there are classes to solve such problems exist, the program only need to create a class object in the program, directly call the object to handle.

2.2 How to create an object entity

In Java, it's also easy to create objects. As long as an operator new can. For example, create a Calendar class object: New GregorianCalendar ();

Three characteristics of 2.3 objects

2.3.1 Object Behavior--can you apply those actions to an object? What methods can be applied to an object?

2.3.2 the state of the object-how does the object respond when those methods are applied?

Identification of the 2.3.3 object-how to identify objects with the same behavior and different states?

3. Method

3.1 What is a method

method, as the name implies, is the way to solve the problem. In C language, methods are generally called functions. It must be clear that the function is also the method, which is the code-level thing that solves the specific problem. This is what the programmer is doing. All computer languages are the same here, and are a line of code that programmers write in accordance with the grammar of the language itself in computer thinking.

3.2 Methods of writing

People who have studied C, know that the definition of a method or function is simple. Define the format in Java: Return value type function name (parameter table column) {statement; ...}

Similarly, there are some modifiers that can be modified, such as the keyword public that modifies access permissions.

4.Java syntax-Objects and classes

4.1 Object and Object variables (class type variables)

We know that to use an object, you must construct the object beforehand, specify its initial state, and then apply the method to the object. In the Java language, a new instance is constructed using the constructor (constructor). A constructor is a special method that is designed to personalize an object when a new object is created. It can be said that the constructor is also called the construction method is object-oriented use. It is now possible to create an object. Here's how:

// now we start using the new operator and the constructor to create the object New Date ();
The new operator is used to create an instance of the class, which is the object, but not all classes need to use the new, for example, if you create an object of type string, you can simply assign a value to complete the creation. If the new operator is used, there will often be a parentheses around the function, which is the constructor part of the class that implements some of the necessary initialization work on the objects of the newly created class.
Anonymous objects: If an object needs to be used only once, you do not have to name it. Use new Date () to create an anonymous date class object.
Object variable: Time is an object variable of a date class, also known as a class type variable. You can compare the definition of the basic data type variable.
// Now let's look at the declaration of a variable of the base data type int age = 18;
Here, we can think of int as the same function as date, that is, the type of age, it is obvious that the number 18 is a standalone object, except that the new operator is not used.

4.2 Data encapsulation and public accessor methods

It is recommended that most instance domain access rights be defined as private. Because if defined as public, any class can freely access and modify the instance domain, which is not only very dangerous, but also violates the encapsulation of the Java language. If we encapsulate the data, then the problem comes, the external class inevitably accesses the data, and does not want the external class to arbitrarily access the modification domain.

At this point, we should provide a common external interface to the data fields to be encapsulated: accessor methods and the change method. In general, we are accustomed to prefix the accessor method name with get, preceded by the change method name prefix set.

    • Sample code
ImportJava.util.GregorianCalendar;ImportJava.util.Calendar;Importjava.util.Date;classemployee{//instance fields, instance domains, member variables    PrivateString name; Private Doublesalary; PrivateDate Hireday; //constructors, constructor     PublicEmployee (String name,DoubleSalaryintYearintMonthintDay ) {         This. Name =name;  This. Salary =salary; GregorianCalendar GC=NewGregorianCalendar (year,month-1, day);  This. Hireday =Gc.gettime (); }    //instance methods, member method//The following are all accessor methods     PublicString GetName () {return  This. Name; }     Public Doublegetsalary () {return  This. Salary; }     PublicDate Gethireday () {return  This. Hireday; }} Public classemployeedemo{ Public Static voidMain (string[] args) {employee[] staff=NewEmployee[3]; staff[0] =NewEmployee ("Mattias Lampe", 2000.0,2015,7,10); staff[1] =NewEmployee ("He Pengfei", 3000.0,2015,8,2); staff[2] =NewEmployee ("Yiu Wenxin", 3120.0,2016,6,16);  for(Employee e:staff) {System.out.println ("Name:" +e.getname () + "Salary:" +e.getsalary () + "Hireday:" +e.gethireday ()); }    }}
    • Code Execution results

4.4 User-defined classes

4.4.1 Instance Domain

The instance field has been created earlier, which is the member variable. The domain is often the property and state of an instance of the class. Most of them are basic data types.

4.4.2 Constructors

constructor, which is the factory that creates the class object. Constructors generally have the following characteristics:

1) The name of the class name;

2) no return value;

3) Support parameter list with no parameter and multiple parameters;

4) is always called with the new operator;

5) Each class can have more than one constructor method.

4.4.3 Implicit parameters

Here, the implicit parameter refers to the This keyword. This has two functions:

1) is used to distinguish between parameter local variables and instance fields (member variables), which is difficult to distinguish if the name is an incoming name local variable or an instance domain of an object, as in the following method

 //  can you tell which name is the local variable name? Which is the instance domain name?  public  void   method (String name) {name  = name;}  //  If you change the above function to the following format, it is easy to distinguish the name from  public  void   method (String name) { this . Name = name;}  //  Of course, many programmers are accustomed to prefix a local variable name with a  public  void   method (String aName) {name  = AName;}  

2) This second usage is to call each other as the constructor itself between multiple constructors

//Suppose there are two constructors here PublicEmployee (String name,intAge ) {     This. Name =name;  This. Age =Age ;}//This is another constructor if you do not use the This keyword PublicEmployee (String name,intAge , String Sex) {     This. Name =name;  This. Age =Age ;  This. Sex =sex;}//Obviously, the code repeats and appears redundant, and if you use the This keyword PublicEmployee (String name,intAge , String Sex) {     This(Name,age);//Another constructor is called here     This. Sex =sex;}

4.5 Static modifier statics

Static modifiers, static can decorate the instance field, and you can decorate the member method. It must be made clear that the static declaration of something that is class-oriented exists. The life cycle of a class is the life cycle of something that is modified by static. Static modifiers do not depend on the existence of an object, but rather on the existence of an object.

    • Sample code
ImportJava.util.Random;classstaticblock{//inistance field, instance field, member variable    PrivateString name; Private intID; Private Static intNextID; //constructors, constructorStaticblock () {} staticblock (String aName) {name=AName; System.out.println ("I'm the constructor, and I'm doing it after the initialization block."); }    //initialization block, initializing blocks, building blocks of code{Name= "Mattias Lampe"; ID=NextID; NextID++; System.out.println ("I am the initialization block also called the Construction code block, object oriented, there is no static initialization block then I am the first to execute"); }    //Static initialization block, statically initialized blocks, statically constructed code blocks    Static{Random Generator=NewRandom (); NextID= Generator.nextint (10000); System.out.println ("I am a static initialization block, class-oriented, I execute earlier than the initialization block and no matter how many times I execute only 1 times"); }    //instance method, member methods     PublicString GetName () {returnName+ "#" +ID; }}classstaticblockdemo{ Public Static voidMain (string[] args) {System.out.println (NewStaticblock (). GetName (). toString ()); System.out.println (NewStaticblock ("Hyundai attempted"). GetName (). toString ()); }}
    • Program execution Results

Summary: Through the Java Grammar Learning, master the Java Grammar Foundation, can write the high quality code. It is almost impossible to remember that these grammars are not a mistake, but to solve the problem constantly, so that you can really master the language of Java. The most effective point, the compiler will tell us there is a problem, how to solve. Sometimes, you have to guess by yourself, and then by writing the appropriate test cases to validate the conjecture, this is one of the quick ways to improve. Of course, a good memory is better than a rotten pen, to remember more to knock code.

[Java Learning note]-java objects and classes

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.