权限修饰符 返回值类型 方法名(参数类型... 参数名)
注意∶ 参数类型和参数名之间是三个点,而不是其他数量或省略号。
顾客买鸡蛋灌饼要求加几个蛋,烙饼大妈就给饼加几个蛋,不要求的时候就只加一个蛋。创建鸡蛋灌饼 EggCake 类,创建有参数和无参数构造方法,无参构造方法调用有参数构造方法并实现初始化。
public class EggCake { // 创建鸡蛋灌饼EggCake类
int eggCount; // 鸡蛋灌饼里蛋的个数(属性)
// 有参数构造方法,参数是给饼加蛋的个数
public EggCake(int eggCount) { // 参数为鸡蛋灌饼里蛋的个数的构造方法
this.eggCount = eggCount; // 将参数eggCount的值付给属性eggCount
System.out.println("这个鸡蛋灌饼里有" + eggCount + "个蛋。");
}
// 无参数构造方法,默认给饼加一个蛋
public EggCake() { // 默认构造方法
// 调用参数为鸡蛋灌饼里蛋的个数的构造方法,并设置鸡蛋灌饼里蛋的个数为1
this(1);
}
public static void main(String[] args) {
EggCake cake1 = new EggCake(); // 创建无参的鸡蛋灌饼对象
EggCake cake2 = new EggCake(5); // 创建鸡蛋灌饼对象,且鸡蛋灌饼里有5个蛋
}
}
定义了两个构造方法,在无参构造方法中可以使用this关键字调用有参的构造方法。但是要注意,this()语句之前不可以有其他代码。
class GasStation {
public int addOil(int oilVolume) {
oilVolume += 2;
return oilVolume;
}
}
public class AutoMobile {
public static void main(String[] args) {
int leftOilVolume = 10;
GasStation gs = new GasStation();
for (int i = 1; i <= 5; i++) {
leftOilVolume = gs.addOil(leftOilVolume);
}
System.out.println("该车现有油量:" + leftOilVolume + "L。");
}
}
public class Cellphone {
public Cellphone() {
System.out.println("智能手机的默认语言为英文");
}
public Cellphone(String defaultLanguage) {
System.out.println("将智能手机的默认语言设置为" + defaultLanguage);
}
public static void main(String[] args) {
Cellphone cellphone1 = new Cellphone();
Cellphone cellphone2 = new Cellphone("中文");
}
}
public class IceBlock {
public IceBlock() {
System.out.println("商家默认可乐里没有冰块……");
}
public IceBlock(String name, int number) {
System.out.println(name + "要求向可乐里放入" + number + "个冰块。");
}
public static void main(String[] args) {
IceBlock block = new IceBlock();
IceBlock iceBlock = new IceBlock("张三", 3);
}
}
public class Teacher {
String name;
char sex;
int age;
public Teacher(String name, char sex, int age) {
this.name = name;
this.sex = sex;
this.age = age;
System.out.println("教师姓名:" + name + "\n教师性别:" + sex + "\n教师年龄:" + age);
}
public static void main(String[] args) {
Teacher chinese = new Teacher("张三", '男', 38);
Teacher math = new Teacher("李四", '男', 45);
Teacher english = new Teacher("王五", '女', 32);
}
}
public class Panda {
private double length = 1.3;
private double weight = 90.0;
public String getMessages() {
return "熊猫体长" + this.length + "米,体重" + this.weight + "KG。";
}
public static void main(String[] args) {
Panda panda = new Panda();
System.out.println(panda.getMessages());
}
}
public class Credit {
String cardNum;
String password;
public Credit(String cardNum, String password) {
this.cardNum = cardNum;
this.password = password;
if (password.equals("123456")) {
System.out.println("信用卡" + cardNum + "的默认密码为" + password);
} else {
System.out.println("重置信用卡" + cardNum + "的密码为" + password);
}
}
public Credit(String cardNum) {
this(cardNum, "123456");
}
public static void main(String[] args) {
Credit initialCredit = new Credit("4013735633800642");
Credit resetedCredit = new Credit("4013735633800642", "168779");
}
}