JAVA class and object (5) ---- object generation and use, java ----
Object generation
Creating an object includes three parts: Object declaration, instantiation, and initialization.
1. Declaration ----- class name Object Name
The Declaration is not to allocate memory space for the object, but to allocate a reference space. An object reference is a 32-bit address space similar to a pointer. Its value points to an intermediate data structure, which stores information about the data type and the heap address of the current object, the actual memory address of the object is not operational, which ensures security.
2. instantiation
The new operator allocates memory space for an object. It calls the object construction method and returns a reference. Different objects of a class occupy different memory spaces.
3. Generate
Initialize the constructor and call the corresponding constructor based on different parameters.
NOTE: If there is no constructor in the class, the system automatically calls the default constructor. The default constructor has no parameters. If a constructor is defined in a class, you must use the constructor defined in the class. Otherwise, an error occurs!
Example:
class Student{ float height,weight; String head,ear,hand,foot,mouth; Student() { height=0; weight=0; head="myhead"; ear="myear"; hand="myhead"; foot="myfoot"; mouth="mymouth"; System.out.println("new Student ok!!!"); } }public class Man{ public static void main(String args[]){ Student zhangsan=new Student(); }}
Object usage
Objects can not only change the state of their own variables, but also have the ability to use methods in the class that creates them. Objects can use these methods to generate certain behaviors, and use the "." operator to access variables and methods. Variables and Methods restrict access to other objects by setting permissions.
1. The object calls its own variable
Object Name. variable name
2. The object calls its own method
Object Name. Method Name (parameter );
Example:
Class Person {float height, weight; String head, ear, hand, foot, mouth; Person () {height = 175; weight = 70; head = "myhead "; ear = "myear"; hand = "myhead"; foot = "myfoot"; mouth = "mymouth"; System. out. println ("new Student OK !!! ");} Void speak (String s) {System. out. println ("say:" + s) ;}} public class Human {public static void main (String args []) {Person zhangsan = new Person (); zhangsan. speak ("hello java !!! "); Person lisi = new Person (); lisi. ear =" "; lisi. speak (" I am studying java !!! ");}}