共计 2148 个字符,预计需要花费 6 分钟才能阅读完成。
一、构造器 (构造方法 | 构造函数)
在创建对象时(new), 必会调用一个特殊的方法,这个方法是初始化对象信息的为 new 服务的。这个方法称为“构造器”
使用 new + 构造方法创建一个新的对象。
构造函数是定义在 Java 类中的一个用来初始化对象的函数。
构造函数与类同名且没有返回值。
例如:Person 类的构造函数:
public class Person { | |
int id; | |
int age; | |
Person(int n, int i){ | |
id = n; | |
age = i; | |
} | |
} |
创建对象时,使用构造函数初始化对象的成员变量
public class Test {public static void main(String[] args) {Person tom = new Person(1, 18); | |
Person jeck = new Person(2, 20); | |
} | |
} |
二、构造方法的特点:
1)名称必须和类名一致,与类名相同
2)没有返回类型 |void
3)构造器可以存在 return,return 有选择的跳出构造器
4)不能随便调用,和 new 在一起使用,其他时候不能调用
5)修饰符不能为 final abstract static
作用:
初始化对象信息,不是用于创建对象的
空构造:
没有参数的构造器、无参构造
1)一个类中,如果没有显示 | 手动 加入 任意构造器 javac 编译后 自动加入空构造
2)一旦加入构造器,javac 不会加入空构造器
三、方法的重载
方法的重载是指一个类中可以定义有相同的方法名,但参数不同的多个方法。调用时,会根据不同的参数列表选择对应的方法。
四、构造方法的重载
与普通方法一样,构造方法也可以重载
例子如下:
五、引用与内存分析
A: 一个对象的内存图
B: 二个对象的内存图
C: 三个对象的内存图
内存分析
划分
引用的特点:
1)同一时刻一个一引用只能指向一个对象
2)一个对象可以被多个引用所指向,其中一个对其进行更改,该对象的其他引用也可见该变化
3)Java 一切为值传递,引用拷贝地址
约定俗成的命名规则
类名的首字母大写
变量名和方法名的首字母小写
运用驼峰标识
例子:
public class Cat { | |
String color; // 毛的颜色 | |
String name; // 名称 | |
public void chase(Mice mice){ | |
mice.type = "jerry"; // 改变 | |
System.out.println(name + "逮" + mice.type); | |
} | |
public static void main(String[] args) { | |
// 引用 与内存分析(运行期为 --》数据的流向)Cat cat = new Cat(); | |
cat = new Cat(); | |
// 引用发生变化,同一个时刻一个引用只能指向一个对象 | |
cat.color = "黑色"; | |
cat.name = "tom"; | |
Mice mice = new Mice(); | |
mice.type = "米奇"; | |
// 将二者联系起来 --》依赖 | |
cat.chase(mice); | |
// 传递时,值拷贝,拷贝地址,拷贝完成后 一个对象被多个引用所指向 | |
System.out.println(mice.type); | |
// jerry 其中一个对其发生变化,该对象的其他引用也可减该变化 | |
} | |
} | |
class Mice{String type;} |
定义如下类
public class BirthDate { | |
int day; | |
int month; | |
int year; | |
public BirthDate(int d, int m, int y){ | |
day = d; | |
month = m; | |
year = y; | |
} | |
void setDay(int d){day = d;} | |
void setMonth(int m){month = m;} | |
void setYear(int y){year = y;} | |
int getDay(){return day;} | |
int getMonth(){return month;} | |
int getYear(){return year;} | |
void display(){System.out.println(day + "-" + month + "-" + year); | |
} | |
} | |
测试类:
public class Test {public static void main(String[] args) {Test test = new Test(); | |
int date = 9; | |
BirthDate d1 = new BirthDate(7,7,1970); | |
BirthDate d2 = new BirthDate(1,1,2000); | |
test.change1(date); | |
test.change2(d1); | |
test.change3(d2); | |
System.out.println(date); | |
System.out.println(d1); | |
System.out.println(d2); | |
} | |
void change1(int i){i = 1234;} | |
void change2(BirthDate b){b = new BirthDate(22,2,2004); | |
} | |
void change3(BirthDate b){b.setDay(22); | |
} | |
} |
总结:
对象的创建和使用,必须使用 new 关键字创建对象,使用对象引用. 成员变量来引用对象的成员变量,使用对象引用. 方法(参数列表)来调用对象的方法。
同一类的每个对象有不同的成员变量存储空间,同一类的每个对象共享该类的方法,
非静态方法是针对每个对象进行调用。
乐字节原创,转载请注明出处。请继续关注乐字节