①定义类
②编写类的成员变量
③编写类的成员方法
public class 类名 {
// 成员变量
变量1的数据类型 变量1;
变量2的数据类型 变量2;
…
// 成员方法
方法1;
方法2;
}
public class Phone {
//成员变量
String brand;
int price;
//成员方法
public void call() {
System.out.println("打电话");
}
public void sendMessage() {
System.out.println("发短信");
}
}
/*
创建对象
格式:类名 对象名 = new 类名();
范例:Phone p = new Phone();
使用对象
1:使用成员变量
格式:对象名.变量名
范例:p.brand
2:使用成员方法
格式:对象名.方法名()
范例:p.call()
*/
public class PhoneDemo {
public static void main(String[] args) {
//创建对象
Phone p = new Phone();
//使用成员变量
System.out.println(p.brand);
p.brand = "小米";
p.price = 2999;
System.out.println(p.brand);
System.out.println(p.price);
//使用成员方法
p.call();
p.sendMessage();
}
}
直接访问类的成员变量是有风险的,因为赋值的类型不一定符号成员变量定义时的变量类型;
所以,在定义class时,可以使用关键字private;
private是一个修饰符,可以用来修饰成员(成员变量,成员方法)
/*
学生类
*/
class Student {
//成员变量
String name;
private int age;
//提供get/set方法
public void setAge(int a) {
if(a<0 || a>120) {
System.out.println("你给的年龄有误");
} else {
age = a;
}
}
public int getAge() {
return age;
}
//成员方法
public void show() {
System.out.println(name + "," + age);
}
}
/*
学生测试类
*/
public class StudentDemo {
public static void main(String[] args) {
//创建对象
Student s = new Student();
//给成员变量赋值
s.name = "林青霞";
s.setAge(30);
//调用show方法
s.show();
}
}
public class Student {
private String name;
private int age;
public void setName(String name) {
this.name = name;//this.name 指代成员变量,name 指代局部变量
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;//this.age 指代成员变量,age指代局部变量
}
public int getAge() {
return age;
}
public void show() {
System.out.println(name + "," + age);
}
}
构造方法是一种特殊的方法
作用:创建对象 Student stu = new Student();
格式:
public class 类名{
修饰符 类名( 参数 ) {
}
}
如果没有定义构造方法,系统将给出一个默认的无参数构造方法
如果定义了构造方法,系统将不再提供默认的构造方法
如果自定义了带参构造方法,还要使用无参数构造方法,就必须再写一个无参数构造方法
无论是否使用,都手工书写无参数构造方法
可以使用带参构造,为成员变量进行初始化
/*
学生类
*/
class Student {
private String name;
private int age;
//无参构造方法
public Student() {}
//带参构造方法
public Student(String name) {
this.name = name;
}
//带参构造方法
public Student(int age) {
this.age = age;
}
//带参构造方法
public Student(String name,int age) {
this.name = name;
this.age = age;
}
public void show() {
System.out.println(name + "," + age);
}
}
/*
测试类
*/
public class StudentDemo {
public static void main(String[] args) {
//创建对象
Student s1 = new Student();//使用无参构造
s1.show();
//public Student(String name)
Student s2 = new Student("林青霞");
s2.show();
//public Student(int age)
Student s3 = new Student(30);
s3.show();
//public Student(String name,int age)
Student s4 = new Student("林青霞",30);
s4.show();
}
}
