



成员变量一般无需指定初始值,存在默认值。
但是局部变量必须定义初始值。
成员变量的默认值:

单词之间不以空格、连接号或者底线连结(例如不应写成:camel case、camel-case或camel_case形式)。共有两种格式:
1、小驼峰式命名法(lower camel case):
第一个单词以小写字母开始,第二个单词的首字母大写。例如:firstName、lastName。
2、大驼峰式命名法(upper camel case):
每一个单词的首字母都采用大写字母,例如:FirstName、LastName、CamelCase,也被称为 Pascal 命名法。

作用:区分局部变量和成员变量,加this调用的是成员变量(即方法外的变量)。
本质:this调用的是地址值。

https://blog.csdn.net/qq_56535449/article/details/125628761
public class Person{
public String name;
public int age;
public double height;
**代码一:**
不用this关键字,直接使用成员变量。
public Person(String name,int a,double height){
name=name;
age=age;
height=height;
}
public void introduce(){
System.out.println("我叫"+name+",今年"+age+"岁");
}
}
public static void main(String[] args){
Person person = new Person("张三",20,178.5);
person.introduce();
}
运行结果
我叫null,今年0岁
**代码二:**
使用this关键字
public Person(String name,int age,double height){
this.name=name;
this.age=age;
this.height=height;
}
public static void main(String[] args){
Person person = new Person("张三",20,178.5);
person.introduce();
}
运行结果:
我叫张三,今年20岁
根据“同名情况下,局部变量的优先级更高”原则
例子:
public class Person{
public String name;
public int age;
public double height;
public void introduce(){
System.out.println("我叫"+name+",今年"+age+"岁");
}
//构造器中加上this关键字
public Person(String name,int age,double height){
this.name=name;
this.age=age;
this.height=height;
}
public static void main(String[] args){
Person person = new Person("张三",20,178.5);
person.introduce();
}
运行结果:
我叫张三,今年20岁
public class Person{
public String name;
public int age;
public double height;
public Person(String name,int a,double height){
name=name;
age=age;
height=height;
}
//增加一个方法
public void greet(){
System.out.println("hello,大家好");
}
public void introduce(){
//在introduce方法中并没有出现其他对象,所以方法名前面的this关键字也可以省略不写。
this.greet();
System.out.println("我叫"+name+",今年"+age+"岁");
}
public static void main(String[] args){
Person person = new Person("张三",20,178.5);
person.introduce();
}
hello,大家好
我叫张三,今年20岁
在this关键字的后面加上小括号,这样就表示调用了某个类自身的构造方法
public class Person{
public String name;
public int age;
public double height;
//构造方法1
public Person(String name,int age,double height){
this(name,age);//调用构造方法2
this.height=height;
}
//构造方法2
public Person(String name,int age){
this.name=name;
this.age=age;
}
//增加一个方法
public void greet(){
System.out.println("hello,大家好");
}
public void introduce(){
//在introduce方法中并没有出现其他对象,所以方法名前面的this关键字也可以省略不写。
this.greet();
System.out.println("我叫"+name+",今年"+age+"岁");
}
public static void main(String[] args){
Person person = new Person("张三",20,178.5);
person.introduce();
}
hello,大家好
我叫张三,今年20岁

构造方法的主要作用就是为对象成员变量赋初始值
每一个类中,会有两种构造方法:空参构造(系统会自动构造)和带参构造(所有参数都需构造)



成员变量使用private修饰





