目录
1、方法的重载(overload/overloading):
4、this:指代当前对象,哪个对象调用方法它指的就是哪个对象
5、构造方法:构造函数、构造器、构建器----------好处:复用给成员变量赋初始值的代码
-
1、方法的重载(overload/overloading):
- 发 生在同一类中,方法名相同,参数列表不同
- 编译器在编译时会根据方法的签名自动绑定调用的方法
-
2、什么是类?什么是对象?
-
现实生活是由很多很多对象组成的,基于对象抽出了类
-
对象:软件中真实存在的单个的个体/东西
类:类型/类别,代表一类个体
-
类是对象的模子/模板,对象是类的具体的实例,可以将类理解为类别/模子/图纸
-
类中可以包含:
-
对象的属性/特征/数据----------------------成员变量
-
对象的行为/动作/功能----------------------方法
-
-
一个类可以创建多个对象
-
-
3、如何创建类?如何创建对象?如何访问成员?
public class Student { //成员变量 String name; int age; String className; String stuId; //方法 void study(){ System.out.println(name+"在学习..."); } void sayHi(){ System.out.println("大家好,我叫"+this.name+",今年"+this.age+"岁了,所在班级为"+this.className+",学号为:"+this.stuId); } void playWith(String anotherName){ System.out.println(this.name+"正在和"+anotherName+"一起玩..."); } } public class StudentTest { public static void main(String[] args) { //创建一个学生对象 Student zs = new Student(); //访问成员变量 zs.name = "张三"; zs.age = 24; zs.className = "jsd2302"; zs.stuId = "001"; //调用方法 zs.study(); zs.sayHi(); zs.playWith("李四"); Student ls = new Student(); ls.name = "李四"; ls.age = 25; ls.className = "jsd2302"; ls.stuId = "002"; ls.study(); ls.sayHi(); ls.playWith("张三"); //1)创建了一个学生对象 //2)给所有成员变量赋默认值 Student ww = new Student(); ww.study(); ww.sayHi(); ww.playWith("张三"); } }
-
4、this:指代当前对象,哪个对象调用方法它指的就是哪个对象
-
只能用在方法中,方法中访问成员变量之前默认有个this.
-
this的用法:
-
this.成员变量名--------------------访问成员变量(必须掌握)
当成员变量与局部变量同名时,若想访问成员变量,则this不能省略
-
this.方法名()-------------------------调用方法(一般不用)
-
this()-----------------------------------调用构造方法(一般不用)
-
-
-
5、构造方法:构造函数、构造器、构建器----------好处:复用给成员变量赋初始值的代码
-
作用:给成员变量赋初始值
-
语法:与类同名,没有返回值类型(连void都没有)
-
调用:在创建(new)对象时被自动调用
-
若自己不写构造方法,则编译器默认提供一个无参构造方法,若自己写了构造方法,则不再默认提供
-
构造方法可以重载
-
public class Student {
//成员变量
String name;
int age;
String className;
String stuId;
//构造方法
Student(){
}
Student(String name,int age){
this.name = name;
this.age = age;
}
Student(String name,int age,String className,String stuId){
this.name = name;
this.age = age;
this.className = className;
this.stuId = stuId;
}
//方法
void study(){
System.out.println(name+"在学习...");
}
void sayHi(){
System.out.println("大家好,我叫"+this.name+",今年"+this.age+"岁了,所在班级为"+this.className+",学号为:"+this.stuId);
}
void playWith(String anotherName){
System.out.println(this.name+"正在和"+anotherName+"一起玩...");
}
}
public class ConsDemo {
public static void main(String[] args) {
Student zs = new Student(); //调用无参构造方法
Student ls = new Student("李四",25); //调用2个参构造
Student ww = new Student("王五",26,"jsd2302","003"); //调用4个参构造
zs.sayHi();
ls.sayHi();
ww.sayHi();
}
}