类的定义
定义一个狗类
class PetDog{
public String name; //名字
public int age; //年龄
// 类方法
public void barks() {
System.out.println(name + "正在叫");
}
}
定义一个学生类
class Student {
public String name;
public short age;
public double score; //三个属性
public void doClass() {};
public void doHomework() {}; //两个类方法
}
注意:
1.
一般一个文件当中只定义一个类
2. main
方法所在的类一般要使用
public
修饰
(
注意:
Eclipse
默认会在
public
修饰的类中找
main
方法
)
3. public
修饰的类必须要和文件名相同
4.
不要轻易去修改
public
修饰的类的名称,如果要修改,通过开发工具修改
。
类的实例化
实例化一个狗 对象
public class task {
public static void main(String[] args) {
PetDog petDog = new PetDog();
petDog.age = 3;
petDog.name = "旺财";
petDog.barks();
}
}
class PetDog{
public String name; //名字
public int age; //年龄
// 类方法
public void barks() {
System.out.println(name + "正在叫");
}
}
如上代码运行结果为
注意:
new
关键字用于创建一个对象的实例
使用 “ . ”
来访问对象中的属性和方法
同一个类可以创建对个实例
对象的构造及初始化
构造方法
概念:构造方法
(
也称为构造器
)
是一个特殊的成员方法,
名字必须与类名相同
,在创建对象时,由编译器自动调用,并且在整个对象的生命周期内只调用一次。
public class Date {
public int year;
public int month;
public int day;
// 构造方法:
// 名字与类名相同,没有返回值类型,设置为void也不行
// 一般情况下使用public修饰
// 在创建对象时由编译器自动调用,并且在对象的生命周期内只调用一次
public Date(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
System.out.println("构造方法被调用了");
}
public void printDate() {
System.out.println(year + "-" + month + "-" + day);
}
public static void main(String[] args) {
Date date1 = new Date(2022,1,1);
date1.printDate();
}
}
构造方法可以重载
public class Date {
public int year;
public int month;
public int day;
// 构造方法:
// 名字与类名相同,没有返回值类型,设置为void也不行
// 一般情况下使用public修饰
// 在创建对象时由编译器自动调用,并且在对象的生命周期内只调用一次
public Date(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
System.out.println("有参数的构造方法被调用了");
}
public Date() {
this.year = 1999;
this.month = 1;
this.day = 1;
System.out.println("没有参数的构造方法被调用了");
}
public void printDate() {
System.out.println(year + "-" + month + "-" + day);
}
public static void main(String[] args) {
Date date1 = new Date();
date1.printDate();
System.out.println("==================="); //分割线 使输出结果容易辨别
Date date2 = new Date(2022,1,1);
date2.printDate();
}
其中有两个构造方法 一个有参数 一个没有参数,实现了方法的重载。当实例化的时候,如果传了参数就会调用有参数的构造方法,如果没有穿参数就会调用没有参数的构造方法。
注意:如果程序员没有写构造方法的代码,java会自动添加一个没有参数的空的构造方法,但是,如果程序员写了构造方法,不管写的构造方法有没有参数,java都不提供构造方法。例如:将上述代码中没有参数的构造方法注释掉,date1的实例化会报错