1) The difference between a member variable and a local variable
1.1) different positions in the class
Member variables: Outside Methods in class
Local variables: In a method definition or on a method declaration
1.2) different locations in memory
Member variables: in the heap
Local variables: in the stack
1.3) Different life cycle
Member variables: As objects are created, they disappear as the object disappears
Local variables: As the method is called, it disappears as the method's call is complete
1.4) different initialization values
Member variables: with default values
Local variables: No default values, must be defined, assigned, and then used
2) Constructor (construction method, constructor)
[<modifier>] <class_name> ([<type arg_name;,..]) {
[<statements>]
}
2.1) Format:
2.1.1) method name and class name are the same
2.1.2) No return value type, even void cannot have
2.1.3) No return value
2.2) Constructor Features:
2.2.1) A class can have multiple builders, but the argument lists of these constructors must be different
2.2.2) Each class will have at least one constructor, and if the constructor is not defined, the system will automatically provide a default constructor with no parameters, and if the class does not have a constructor, it can be constructed with this default to build an object. Recommended: Always manually give a non-parametric construction method.
2.3) Role of the constructor
Used to initialize the data of an object. Create an object from the constructor, and use the New keyword to create an object called a constructor in the class after new.
2.4) How to assign a value to a member variable
2.4.1) setxxx ()
2.4.2) with parameter construction method
2.5) Case
Class Student {private String name;private int age;public Student () {}public Student (String name,int age) {this.name = name ; this.age = age;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;}}
2.5.1) test
Class Studentdemo {public static void main (string[] args) {//mode 1Student S1 = new Student (); S1.setname ("Zhang San"); S1.setage (27) ; System.out.println (S1.getname () + "---" +s1.getage ());//mode 2Student s2 = new Student ("John Doe", 30); System.out.println (S2.getname () + "---" +s2.getage ());}}
This article is from "Never give up!" Ningzhiyuan "blog, declined reprint!
Java member/local variables and constructors summary