Class object (1) java in

       First, understand what the relationship between classes and objects, we can say: class is an abstract object, the object is an instance of the class.

class

     A class usually contains the attributes and functions. Usually variable properties expressed by the function is usually expressed as a function. Write a class

   class class name {

       // property, with variable expression

       // function, expression with function

    }

Objects  

     Examples of the object's method and meanings : class name = new class name of the object name () ;, e.g.: Student Student zhangsan = new ().

     Meaning: the equal sign in front of the object corresponding to the definition of a name, a Student type, called an object reference , then no memory allocation to null value (null); equal sign to the reference point to an actual object, the assigned the corresponding memory. ( Keyword new memory allocation )

Access to member variables  

      java is not a pointer, unified with. to access that object name. member variable name, for example zhangsan.name represent objects zhangsan access member variables name. Reference method is the same.

Note: The object name is a reference to its contents when the assignment is not the object of the assignment, but will be assigned by reference. I.e., if the statement Student lisi = zhangsan; then the time will lisi zhangsan and the same object (like pointers), to the time after the assignment lisi.name zhangsan.name will also change. lisi originally pointed object will be discarded as garbage collection last.

example:

class Student{

    public String name; // class attributes

    public String sex;

    public Int age;

    // class functionality

    void display(){

        System.out.println("name=" + name);

        System.out.println("sex=" + sex);

        System.out.println("age=" + age);

    }

}

public class Test{

    public static void main (String [] args) {// main function

        Student zhangsan = new Student (); // instantiate objects

        zhangsan.name = "John Doe";

        zhangsan.sex = "男";

        zhangsan.age = 19;

        zhangsan.display (); // call the class output method: name = Zhang sex = age = 19 M

        Student lisi = zhangsan; // lisi case as the properties and zhangsan

        lisi.display (); // Output: name = Zhang sex = age = 19 M

        zhangsan.age = 20;

        System.out.println("lisi.age=" + lisi.age);//输出:lisi.age=20

    }

}

 

Guess you like

Origin www.cnblogs.com/541wsy/p/12470420.html