new构建的新对象拥有这个类里所有的属性,new出来的对象存储在heap堆里,构造方法和类名要完全一致,并且没有返回值
练习程序:Person(int _id, int _age)就是构造方法,Person tom = new Person(1,25)是new和构造方法同时使用的实例
public class Person {
int id;
int age = 20;
Person(int _id, int _age) {
id = _id;
age = _age;
}
public static void main(String[] args) {
Person tom = new Person(1,25);
Person jerry= new Person(1,20);
Point p = new Point();
}
}
class Point {
Point() {}
int x;
int y;
}
内存的调用:方法调用完栈里的空间马上释放,因为方法完成之后局部变量就没有了。
Point p = new Point();是利用编译器默认的Point () {}空的构造方法,int x 和int y默认初始为0.
内存调用分析程序:
class BirthDate {
private int day;
private int month;
private int year;
public BirthDate(int d, int m, int y) {
day = d;
month = m;
year = y;
}
public void setDay(int d) {
day = d;
}
public void setMonth(int m) {
month = m;
}
public void setYear(int y) {
year = y;
}
public int getDay() {
return day;
}
public int getMonth() {
return month;
}
public int getYear() {
return year;
}
public 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=" + date);
d1.display();
d2.display();
}
public void change1(int i){
i = 1234;
}
public void change2(BirthDate b) {
b = new BirthDate(22,2,2004);
}
public void change3(BirthDate b) {
b.setDay(22);
}
}
1).class BirthDate前面不用加public吗 加和不加有什么区别
2).听分析的很明白, 自己分析不出来。
重载:overload,方法名一样,但参数不一样(类型不一样或者个数不一样),只要编译器调用方法时能够区分开就能构。成重载
public class Test {
void max(int a , int b) {
System.out.println( a > b ? a : b );
}
void max(short a , short b) {
System.out.println("short");
System.out.println( a > b ? a : b );
}
void max(float a, float b) {
System.out.println( a > b ? a : b );
}
public static void main(String[] args) {
Test t = new Test();
t.max(3, 4);
short a = 3;
short b = 4;
t.max(a, b);
}
}