Java-07,Java类的定义,内存解析
//用class关键字定义一个类,例如: public class Person { //成员变量定义 private int id; private int age = 20; //方法定义 public int getAge(){ return age; } public void setAge(int i){ age = i; } public int getId(){ return id; } public void setId(int i){ id = i; } public static void main(String args[]){ Person p1 = new Person(); System.out.println("Age="+p1.age); p1.setAge(24); p1.setId(1); System.out.println("Id="+p1.id+"\nAge="+p1.age); } }
- 类的定义主要有两方面组成——成员变量和方法。
- 声明成员变量的格式为:[<modifiers>] type <attr_name>[=defaultValue];
- 例如:private int id; private int age = 20;
- 声明方法的格式为:
- 声明成员变量的格式为:[<modifiers>] type <attr_name>[=defaultValue];
[<modifiers>] <modifiers> <return_type> <name> ([argu_list]){
[<statements>]
}
-
-
- 例如:public int getAge(){
-
return age;
}
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); } }
运行结果:
date=9
7/7/1970
22/1/2000
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步