// 定义Student类
class Student {
String name;
int age;
int studentId;
public void get() {
System.out.println("姓名:" + name + " 年龄:" + age + " 学号:" + studentId);
}
}
// 定义HelloWorld类
public class HelloWorld {
// 程序入口 main
public static void main(String[] args) {
Student obj = new Student(); // 创建对象
obj.get(); // null, 0, 0
// 修改对象的属性值
obj.name = "Peter";
obj.age = 16;
obj.studentId = 1024255;
obj.get(); // Peter, 16, 1024255
}
}
this : 主要用于解决变量名称冲突问题
public class HelloWorld {
public static void main(String[] args) {
Student obj = new Student();
System.out.println("姓名:" + obj.name + " 年龄:" + obj.age + " 学号:" + obj.studentId);
obj.setAttr("Gogo", 33, 1024255);
System.out.println("姓名:" + obj.name + " 年龄:" + obj.age + " 学号:" + obj.studentId);
// 运行结果:
// 姓名:null 年龄:0 学号:0
// 姓名:Gogo 年龄:33 学号:1024255
}
}
class Student {
String name;
int age;
int studentId;
public void setAttr(String name, int age, int studentId) {
this.name = name;
this.age = age;
this.studentId = studentId;
}
}
构造器
public class HelloWorld {
public static void main(String[] args) {
Student obj = new Student("Peter", 20, 1024255);
System.out.println("姓名:" + obj.name + " 年龄:" + obj.age + " 学号:" + obj.studentId);
// 运行结果:
// 含参构造器被触发执行了
// 姓名:Peter 年龄:20 学号:1024255
}
}
class Student {
String name;
int age;
int studentId;
// (无参)构造器 [支持重载]
public Student() {
System.out.println("无参构造器被触发执行了");
}
// (含参)构造器 [支持重载]
public Student(String name, int age, int studentId) {
System.out.println("含参构造器被触发执行了");
this.name = name;
this.age = age;
this.studentId = studentId;
}
}
三大特征
封装 ( 合理隐藏,合理暴露 )
public class HelloWorld {
public static void main(String[] args) {
People jack = new People(29);
System.out.println(jack.getAge()); // 29
jack.setAge(56);
System.out.println(jack.getAge()); // 56
jack.setAge(-1); // Error! The age is incorrect!
}
}
class People {
private int age; // 禁止直接访问与修改age
public People(int age) {
this.age = age;
}
// 对外提供访问、修改 age 的方法
public int getAge() {
return age;
}
public void setAge(int age) {
if (age > 0 && age <= 120) {
this.age = age;
} else {
System.out.println("Error! The age is incorrect!");
}
}
}
继承:Java 基础阶段不作介绍
多态:Java 基础阶段不作介绍