In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is about how to use Java to comprehensively analyze classes and objects, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
Process-oriented? object-oriented?
C language is a process language, which pays attention to the process when solving problems, so C language is process-oriented.
JAVA language is different, JAVA language is an object-oriented language, when solving a problem, the problem is divided into several objects, and the objects interact with each other to solve the problem. Object is the core of JAVA language.
When designing and developing with JAVA, what we need to do is to find objects, establish objects, use objects, and maintain the relationship between objects.
II. Instantiation of classes and classes
A class is actually a general term for a class of objects, equivalent to a template; an object is actually the result of instantiating a class, equivalent to a sample generated by a template.
A template can produce multiple samples, and a class can instantiate multiple objects.
In JAVA, a class is a reference type, and the keyword class is needed to declare a class, which is actually equivalent to creating a new data type.
Basic grammatical forms:
/ / create a class class {field;// member variable method;// member method} / / instantiate an object = new (); 2.1 normal member variables and ordinary member methods
Code example:
Class Person {public int age; public String name;// member variable is placed in the object, that is, public void show () {/ / int a = 10 on the heap; / / a variable is defined in the method, it is not a member variable, it is a local variable, and memory System.out.println is opened on the stack ("name:" + name + "age:" + age) }} public class TestDemo {public static void main (String [] args) {Person person1 = new Person (); person1.age = 18; person1.name = "Fuchun"; person1.show (); Person person2 = new Person (); person2.age = 21; person2.name = "Mountain dwelling"; person2.show ();}}
Code result:
Code interpretation:
The Person class is created here with the keyword class (the class name is usually the big hump, that is, the first letter of each word is capitalized).
Variables such as age and name that are defined inside the class outside the method are called member variables or properties or fields. In addition, these two variables are ordinary member variables.
A method or behavior that describes the behavior of an object like show is called a method or behavior, where the name and age are printed by the show method. In addition, this method is an ordinary member method.
In JAVA, the member variables and methods of the class are accessed through the instance (object) dot (.) of the class. The format is: object name. Member variable; object name. Member methods (argument list); (PS: when accessing a member method of a class, if the method of the class has a tangible parameter, you must pass the same argument value as the parameter type for the method.)
In the main function, two objects are instantiated, opening up memory on the heap, and the address of the memory is stored in person1 and person2, so the two variables are actually reference variables. The new keyword is used to create an instance of an object.
Memory distribution:
Note:
When the member variables in the object are not assigned an initial value, the reference type defaults to null, the basic type defaults to 0, the boolean type defaults to false, and the char type defaults to'\ u0000' (which means nothing).
When the variable of the reference type is null, it means that no object is referenced. When you access null, a null pointer exception occurs.
If you don't want the member variable to use the default value, you can assign the initial value to the member variable when you create the class, but it doesn't make much sense. The class is a template after all, creating a variety of samples.
Code example:
Class Person {public int age; public String name; public boolean ans; public char ch; public void show () {System.out.println ("name:" + name + "age:" + age); System.out.println ("ans:" + ans + "ch:" + ch);}} public class TestDemo {public static void main (String [] args) {Person person = new Person () Person.show ();}}
? Code result:
2.2 static member variables and static member methods
Code example:
Class Person {public int age; public static int count; public static final int COUNT = 99; / / COUNT is a static constant public static void staticTest () {System.out.println ("this is a static member method");}} public class TestDemo {public static void main (String [] args) {Person person1 = new Person (); person1.age = 18; Person.count = 20 System.out.println (person1.age + "" + Person.count); Person.staticTest ();}}
Code result:
Code interpretation:
Member variables modified with the static keyword are called static member variables, and modified member methods are called static member methods.
Access to a normal member variable or method requires an object to be instantiated and accessed by reference. However, static member variables or static member methods do not need to create instance objects and are accessed directly through the class name in the format: class name. Member variable; class name. Member method (argument list)
Static member variables or methods are shared by different instances of the same class and do not belong to objects. They are stored in the method area and only one copy exists.
Memory distribution:
Note:
Static methods cannot directly use non-static member variables or non-static methods. Because the latter two are instance-related, you need to instantiate the object if you need to use it, while static methods are instance-independent and class-dependent, so you can't call them directly. This is why other methods are called in the main function, preferably static methods.
So why does the main function have to be static? What if it's not static?
Assuming that the main function is not a static function, then if you want to call the main function, you must enter the main function, instantiate the object, and call the main function through reference, but the problem is that the main function has not been called at all, how to get into the main function? This creates a logical dead loop, and the only solution is to set the main function to static and call it through the Java virtual machine.
III. Encapsulation
In object-oriented programming, encapsulation encapsulates the resources needed for an object to run in a program object-- basically, methods and data. The object is to "publish its interface". Other objects attached to these interfaces do not need methods that care about the object implementation to use this object. The concept is, "Don't tell me how you do it, just do it."
3.1 private
Both properties and methods have their own access rights, and the keyword private/ public means "access control"
Public: public indicates that the data member and member function are open to all users, and all users can call them directly.
Private: private means private, which means that no one can use it directly except class itself.
In the code example in the first paragraph of this chapter, when the member variables age and name are modified by public, the following problems may occur:
Consumers of a class must understand the internal implementation of the Person class before they can use it. The cost of learning is high. If the implementer of the Person class modifies the name of the member variable, the user of the class needs to change their code accordingly. If the project is large, it will lead to high maintenance costs.
The access permissions of each member variable or method need to be carefully considered on a case-by-case basis, and should not be arbitrarily set to public.
In this way of thinking, the private keyword is particularly important. The properties modified by it cannot be directly used by the users of the class (they are not accessed at all). You need to use the getter and setter methods described below, so that you do not have to know the implementation details of the class.
3.2 getter and setter
When decorating a field with private, if you need to get or modify the private property, you need to use the getter and setter methods
Code example:
Class Person {private int age; private String name; public int getAge () {return age;} public void setAge (int myAge) {age = myAge;} public void setName (String myMame) {name = myMame;} public String getName () {return name } public void show () {System.out.println ("name:" + name + "Age:" + age);}} public class TestDemo {public static void main (String [] args) {Person person1 = new Person (); person1.setAge (18); person1.setName ("Fuchun"); int age = person1.getAge (); String name = person1.getName () System.out.println (name + "" + age); person1.show ();}}
Code result:
Code interpretation:
GetName and getAge are the getter methods, which means to get the value of this member
SetName and setAge are the setter methods, which set the value of this member.
IV. Construction method
There are two steps to instantiating an object:
one. Allocate memory space for objects
two。 Call the constructor of the object (there is more than one constructor)
Constructor is a special method, which is called automatically when a new object is instantiated with the keyword new, which can not only construct the object, but also help us initialize the member variables.
4.1 basic Grammar
Rules:
The method name and class name are the same, and there is no return value
When no constructor is provided in the class, the compiler generates a constructor without arguments by default.
If a constructor is defined in the class, the constructor without parameters will not be generated by default
The constructor supports overloading, and the overloading of rules is consistent with that of common methods.
Code example:
Class Person {private int age; private String name; public Person () {System.out.println ("Construction method without parameters");} public Person (String name) {this.name = name; System.out.println ("Construction method with one Parameter");} public Person (String name,int age) {this.name = name; this.age = age System.out.println ("Construction method with two parameters");} public void show () {System.out.println ("name:" + this.name + "Age:" + this.age);}} public class TestDemo {public static void main (String [] args) {Person person1 = new Person (); person1.show (); Person person2 = new Person ("Fuchun") Person2.show (); Person person3 = new Person ("Mountain residence", 18); person3.show ();}}
Code result:
4.2 this keyword
There are a lot of this keywords in the previous code, so what does this keyword stand for?
This keyword is used during the construction of the object, and the object has not been constructed yet, so it does not represent the current object, the this keyword represents the reference to the current object
You can use the this keyword to access member variables and member methods of an object, or you can use it to call other constructors
Methods:
This. Member variable
This. Member method
This ()
Note:
When calling other constructors with the this keyword, be sure to place the this keyword in the first line of static methods, because the keyword represents a reference to the current object, and static methods are independent of the object.
Code example:
Class Person {private int age; private String name; public Person () {this ("Fuchun", 18); / / call other constructors System.out.println ("constructors without parameters");} public Person (String name,int age) {this.name = name; this.age = age; System.out.println ("constructors with two parameters") } public void show () {System.out.println ("name:" + this.name + "Age:" + this.age);}} public class TestDemo {public static void main (String [] args) {Person person1 = new Person (); person1.show ();}}
Code result:
Adding the this keyword is a good code habit.
5. Code block
The code form in Java that encloses multiple lines of code with curly braces {} and forms a separate code interval is called code block, which is a common code form in Java.
According to the location of the code block definition and keywords, it can be divided into the following four categories: ordinary code block, construction code block, static code block, synchronous code block.
Next, we will mainly introduce the first three, and the last one will cover the multithreading part.
5.1 normal code block
It is the most common code block, the method body of a method in a class or after the method name.
Code example:
Public class TestDemo {public static void main (String [] args) {int a = 10; {int b = 20; System.out.println (b);} System.out.println (a);}}
Code interpretation:
Here, the content wrapped by {} followed by the main method is a normal code block, and the content in {} wrapped by the code that defines the variable b and prints it is also a normal code block.
5.2 construct a code block
An unmodified code block defined in a class is called a construction code block, also known as an instance code block. The construction code block is generally used to initialize instance member variables.
Code example:
Class Person {private int age; private String name; {this.name = "mountain residence"; this.age = 18;} public void show () {System.out.println ("name:" + this.name + "age:" + this.age);}} 5.3 static code block
Code blocks defined by static are generally used to initialize static member attributes and some data that needs to be prepared in advance
Code example:
Class Person {private int age; private String name; public static int count; static {count = 20;} public void show () {System.out.println ("name:" + this.name + "Age:" + this.age) Note Construction code block takes precedence over constructor execution static code block takes precedence over construction code block execution, and for the same class only once execution of the contemporary code block and member variables are static or instance, the order of their values and definitions is the related shortcut method 6.1 toString method
In the first code example of this chapter, the properties of the object are printed in the class through the show method, but when there are many properties, it is not so convenient. Therefore, you can use keyboard shortcuts.
Step 1: alt + insert or right-click to select Generate (to be executed in the code area of the class)
Step 2: select toString ()
Step 3: select the attributes to be printed
Step 4: select OK
Code example:
Class Person {public int age; public String name; @ Override public String toString () {return "Person {" + "age=" + age + ", name='" + name +'\'+'}';}} public class TestDemo {public static void main (String [] args) {Person person1 = new Person (); person1.age = 18 Person1.name = "Fuchun"; System.out.println (person1);}}
Code result:
Code interpretation:
@ Override is an annotation used to explain that the method is overridden when the toString method is not overridden, print person1, which will be an address
When the toString method is overridden, the print person1 will directly call the toString method 6.2setter / getter method
Setter / getter methods can also be generated automatically using shortcut keys
Step 1: alt + insert or right-click to select Generate (to be executed in the code area of the class)
Step 2: select Getter and Setter
Step 3: select the properties that require this method
Step 4: select OK
? Code example:
Class Person {private int age; private String name; public int getAge () {return age;} public void setAge (int age) {this.age = age; / / age = age; error} public String getName () {return name;} public void setName (String name) {this.name = name } public void show () {System.out.println ("name:" + name + "age:" + age);}}
? Code interpretation:
When the automatically generated setter method parameter name is the same as the name of the member property in the class, if you do not use this, it is equivalent to a self-assigned value. This represents a reference to the current object
6.3 Construction method (fast)
There are also shortcuts when you want to quickly generate constructors with a different number of parameters.
Step 1: alt + insert or right-click to select Generate (to be executed in the code area of the class)
Step 2: select Constructor
Step 3: select the properties that require this method
Step 4: select OK (if there is no parameter, skip step 3 and select Select None directly)
? Code example:
Class Person {private int age; private String name; public Person () {} public Person (String name) {this.name = name;} public Person (int age, String name) {this.age = age; this.name = name;}} above is how to use Java to fully analyze classes and objects. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.