1型诚、定義三個重載方法max()客燕,第一個方法,返回兩個int值中的最大值俺驶,
第二個方法幸逆,返回兩個double值中的最大值棍辕,第三個方法,
返回三個double值中的最大值还绘,并分別調用三個方法
public class MaxValue {
// 返回兩個int值中的最大值
public static int max(int a, int b) {
return (a > b) ? a : b;
}
// 返回兩個double值中的最大值
public static double max(double a, double b) {
return (a > b) ? a : b;
}
// 返回三個double值中的最大值
public static double max(double a, double b, double c) {
return max(max(a, b), c);
}
public static void main(String[] args) {
// 調用第一個max方法
int intMax = max(3, 7);
System.out.println("Max of 3 and 7 is: " + intMax);
// 調用第二個max方法
double doubleMax = max(4.5, 2.3);
System.out.println("Max of 4.5 and 2.3 is: " + doubleMax);
// 調用第三個max方法
double tripleMax = max(1.2, 3.4, 2.8);
System.out.println("Max of 1.2, 3.4 and 2.8 is: " + tripleMax);
}
}
2楚昭、編寫程序,類Methods中定義三個重載方法并調用拍顷。方法名為m抚太。
三個方法分別接收一個int參數(shù)、兩個int參數(shù)昔案、一個字符串參數(shù)尿贫。分別執(zhí)行平方運算并輸出結果,
相乘并輸出結果踏揣,輸出字符串信息庆亡。在主類的main ()方法中分別用參數(shù)區(qū)別調用三個方法
public class Methods {
// 接收一個int參數(shù),執(zhí)行平方運算并輸出結果
public void m(int a) {
int result = a * a;
System.out.println("Square of " + a + " is: " + result);
}
// 接收兩個int參數(shù)捞稿,相乘并輸出結果
public void m(int a, int b) {
int result = a * b;
System.out.println("Product of " + a + " and " + b + " is: " + result);
}
// 接收一個字符串參數(shù)又谋,輸出字符串信息
public void m(String message) {
System.out.println("Message: " + message);
}
public static void main(String[] args) {
// 創(chuàng)建 Methods 類的實例
Methods methods = new Methods();
// 分別調用三個重載方法
methods.m(5); // 調用第一個方法,輸出 5 的平方
methods.m(3, 7); // 調用第二個方法娱局,輸出 3 和 7 的乘積
methods.m("Hello"); // 調用第三個方法彰亥,輸出字符串 "Hello"
}
}
3、用封裝實現(xiàn)不能隨便查看人的年齡,工資等隱私衰齐,并對設置的年齡進行合理的驗證任斋。年齡合理就設置,否則給默認年齡, 必須在 1-120, 年齡耻涛, 工資不能直接查看 废酷, name的長度在 2-6字符 之間
public class Person {
// 私有變量,不能直接訪問
private String name;
private int age;
private double salary;
// 公有方法來訪問和修改這些變量
// 獲取姓名
public String getName() {
return name;
}
// 設置姓名犬第,驗證長度在2-6字符之間
public void setName(String name) {
if (name != null && name.length() >= 2 && name.length() <= 6) {
this.name = name;
} else {
System.out.println("Invalid name length. Name should be between 2 and 6 characters.");
this.name = "Default";
}
}
// 獲取年齡
public int getAge() {
return age;
}
// 設置年齡锦积,驗證在1-120之間
public void setAge(int age) {
if (age >= 1 && age <= 120) {
this.age = age;
} else {
System.out.println("Invalid age. Age should be between 1 and 120.");
this.age = 18; // 默認年齡
}
}
// 獲取工資
public double getSalary() {
return salary;
}
// 設置工資
public void setSalary(double salary) {
this.salary = salary;
}
public static void main(String[] args) {
Person person = new Person();
// 設置姓名并獲取
person.setName("John");
System.out.println("Name: " + person.getName());
person.setName("J");
System.out.println("Name: " + person.getName());
// 設置年齡并獲取
person.setAge(25);
System.out.println("Age: " + person.getAge());
person.setAge(150);
System.out.println("Age: " + person.getAge());
// 設置工資并獲取
person.setSalary(5000);
// 因為工資是隱私,所以不直接輸出
System.out.println("Salary: " + person.getSalary());
}
}
4歉嗓、封裝實現(xiàn)創(chuàng)建程序,在其中定義兩個類:Account和AccountTest類體會Java的封裝性。
- Account類要求具有屬性:姓名(長度為2位3位或4位)背蟆、余額(必須>20)鉴分、
- 密碼(必須是六位), 如果不滿足,則給出提示信息带膀,并給默認值(程序員自己定)
- 通過setXxx的方法給Account 的屬性賦值志珍。
- 在AccountTest中測試
Account 類
public class Account {
// 私有屬性
private String name;
private double balance;
private String password;
// 獲取姓名
public String getName() {
return name;
}
// 設置姓名,驗證長度為2位垛叨、3位或4位
public void setName(String name) {
if (name != null && (name.length() == 2 || name.length() == 3 || name.length() == 4)) {
this.name = name;
} else {
System.out.println("Invalid name length. Setting default name.");
this.name = "Default";
}
}
// 獲取余額
public double getBalance() {
return balance;
}
// 設置余額伦糯,驗證必須大于20
public void setBalance(double balance) {
if (balance > 20) {
this.balance = balance;
} else {
System.out.println("Invalid balance. Setting default balance.");
this.balance = 20.0; // 默認余額
}
}
// 獲取密碼
public String getPassword() {
return password;
}
// 設置密碼柜某,驗證必須是六位
public void setPassword(String password) {
if (password != null && password.length() == 6) {
this.password = password;
} else {
System.out.println("Invalid password length. Setting default password.");
this.password = "123456"; // 默認密碼
}
}
}
AccountTest 類
public class AccountTest {
public static void main(String[] args) {
Account account = new Account();
// 測試設置姓名
account.setName("Tom");
System.out.println("Name: " + account.getName());
account.setName("Alexander");
System.out.println("Name: " + account.getName());
// 測試設置余額
account.setBalance(50);
System.out.println("Balance: " + account.getBalance());
account.setBalance(10);
System.out.println("Balance: " + account.getBalance());
// 測試設置密碼
account.setPassword("654321");
System.out.println("Password: " + account.getPassword());
account.setPassword("abc");
System.out.println("Password: " + account.getPassword());
}
}
5、繼承實現(xiàn)編寫Computer類敛纲,包含CPU喂击、內存、硬盤等屬性淤翔,getDetails方法用于返回Computer的詳細信息
編寫PC子類翰绊,繼承Computer類,添加特有屬性【品牌brand】
編寫NotePad子類旁壮,繼承Computer類监嗜,添加特有屬性【color】//同學們自己寫。
編寫Test類抡谐,在main方法中創(chuàng)建PC和NotePad對象裁奇,分別給對象中特有的屬性賦值,
以及從Computer類繼承的屬性賦值麦撵,并使用方法并打印輸出信息
Computer 類
public class Computer {
private String cpu;
private int memory;
private int storage;
// 構造方法
public Computer(String cpu, int memory, int storage) {
this.cpu = cpu;
this.memory = memory;
this.storage = storage;
}
// 獲取詳細信息的方法
public String getDetails() {
return "CPU: " + cpu + ", Memory: " + memory + "GB, Storage: " + storage + "GB";
}
// Getter 和 Setter 方法
public String getCpu() {
return cpu;
}
public void setCpu(String cpu) {
this.cpu = cpu;
}
public int getMemory() {
return memory;
}
public void setMemory(int memory) {
this.memory = memory;
}
public int getStorage() {
return storage;
}
public void setStorage(int storage) {
this.storage = storage;
}
}
PC 子類
public class PC extends Computer {
private String brand;
// 構造方法
public PC(String cpu, int memory, int storage, String brand) {
super(cpu, memory, storage);
this.brand = brand;
}
// 獲取詳細信息的方法
@Override
public String getDetails() {
return super.getDetails() + ", Brand: " + brand;
}
// Getter 和 Setter 方法
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
}
NotePad 子類
public class NotePad extends Computer {
private String color;
// 構造方法
public NotePad(String cpu, int memory, int storage, String color) {
super(cpu, memory, storage);
this.color = color;
}
// 獲取詳細信息的方法
@Override
public String getDetails() {
return super.getDetails() + ", Color: " + color;
}
// Getter 和 Setter 方法
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
Test 類
public class Test {
public static void main(String[] args) {
// 創(chuàng)建PC對象
PC pc = new PC("Intel i7", 16, 512, "Dell");
System.out.println("PC Details: " + pc.getDetails());
// 創(chuàng)建NotePad對象
NotePad notePad = new NotePad("AMD Ryzen 5", 8, 256, "Silver");
System.out.println("NotePad Details: " + notePad.getDetails());
}
}
6刽肠、通過super關鍵字實現(xiàn)當創(chuàng)建子類對象時,不管使用子類的哪個構造器厦坛,默認情況下總會去調用父類的無參構造器五垮,如果父類沒有提供無參構造器,則必須在子類的構造器中用 super 去指定使用父類的哪個構造器完成對父類的初始化工作杜秸,否則放仗,編譯不會通過
父類 Computer
public class Computer {
private String cpu;
private int memory;
private int storage;
// 無參構造器
public Computer() {
System.out.println("Computer's no-arg constructor called");
}
// 有參構造器
public Computer(String cpu, int memory, int storage) {
this.cpu = cpu;
this.memory = memory;
this.storage = storage;
System.out.println("Computer's parameterized constructor called");
}
// 獲取詳細信息的方法
public String getDetails() {
return "CPU: " + cpu + ", Memory: " + memory + "GB, Storage: " + storage + "GB";
}
// Getter 和 Setter 方法
public String getCpu() {
return cpu;
}
public void setCpu(String cpu) {
this.cpu = cpu;
}
public int getMemory() {
return memory;
}
public void setMemory(int memory) {
this.memory = memory;
}
public int getStorage() {
return storage;
}
public void setStorage(int storage) {
this.storage = storage;
}
}
使用 super 關鍵字可以顯式調用父類的構造器。在子類構造器中撬碟,如果沒有指定調用父類構造器诞挨,Java會默認調用父類的無參構造器。如果父類沒有無參構造器呢蛤,必須在子類構造器中使用 super 關鍵字指定調用父類的有參構造器惶傻。以下是一個示例實現(xiàn)。
父類 Computer
java
public class Computer {
private String cpu;
private int memory;
private int storage;
// 無參構造器
public Computer() {
System.out.println("Computer's no-arg constructor called");
}
// 有參構造器
public Computer(String cpu, int memory, int storage) {
this.cpu = cpu;
this.memory = memory;
this.storage = storage;
System.out.println("Computer's parameterized constructor called");
}
// 獲取詳細信息的方法
public String getDetails() {
return "CPU: " + cpu + ", Memory: " + memory + "GB, Storage: " + storage + "GB";
}
// Getter 和 Setter 方法
public String getCpu() {
return cpu;
}
public void setCpu(String cpu) {
this.cpu = cpu;
}
public int getMemory() {
return memory;
}
public void setMemory(int memory) {
this.memory = memory;
}
public int getStorage() {
return storage;
}
public void setStorage(int storage) {
this.storage = storage;
}
}
使用 super 關鍵字可以顯式調用父類的構造器其障。在子類構造器中银室,如果沒有指定調用父類構造器,Java會默認調用父類的無參構造器励翼。如果父類沒有無參構造器蜈敢,必須在子類構造器中使用 super 關鍵字指定調用父類的有參構造器。以下是一個示例實現(xiàn)汽抚。
父類 Computer
java
public class Computer {
private String cpu;
private int memory;
private int storage;
// 無參構造器
public Computer() {
System.out.println("Computer's no-arg constructor called");
}
// 有參構造器
public Computer(String cpu, int memory, int storage) {
this.cpu = cpu;
this.memory = memory;
this.storage = storage;
System.out.println("Computer's parameterized constructor called");
}
// 獲取詳細信息的方法
public String getDetails() {
return "CPU: " + cpu + ", Memory: " + memory + "GB, Storage: " + storage + "GB";
}
// Getter 和 Setter 方法
public String getCpu() {
return cpu;
}
public void setCpu(String cpu) {
this.cpu = cpu;
}
public int getMemory() {
return memory;
}
public void setMemory(int memory) {
this.memory = memory;
}
public int getStorage() {
return storage;
}
public void setStorage(int storage) {
this.storage = storage;
}
}
使用 super 關鍵字可以顯式調用父類的構造器抓狭。在子類構造器中,如果沒有指定調用父類構造器造烁,Java會默認調用父類的無參構造器否过。如果父類沒有無參構造器午笛,必須在子類構造器中使用 super 關鍵字指定調用父類的有參構造器。以下是一個示例實現(xiàn)苗桂。
父類 Computer
java
public class Computer {
private String cpu;
private int memory;
private int storage;
// 無參構造器
public Computer() {
System.out.println("Computer's no-arg constructor called");
}
// 有參構造器
public Computer(String cpu, int memory, int storage) {
this.cpu = cpu;
this.memory = memory;
this.storage = storage;
System.out.println("Computer's parameterized constructor called");
}
// 獲取詳細信息的方法
public String getDetails() {
return "CPU: " + cpu + ", Memory: " + memory + "GB, Storage: " + storage + "GB";
}
// Getter 和 Setter 方法
public String getCpu() {
return cpu;
}
public void setCpu(String cpu) {
this.cpu = cpu;
}
public int getMemory() {
return memory;
}
public void setMemory(int memory) {
this.memory = memory;
}
public int getStorage() {
return storage;
}
public void setStorage(int storage) {
this.storage = storage;
}
}
子類PC
public class PC extends Computer {
private String brand;
// 無參構造器
public PC() {
super(); // 調用父類的無參構造器
System.out.println("PC's no-arg constructor called");
}
// 有參構造器
public PC(String cpu, int memory, int storage, String brand) {
super(cpu, memory, storage); // 調用父類的有參構造器
this.brand = brand;
System.out.println("PC's parameterized constructor called");
}
// 獲取詳細信息的方法
@Override
public String getDetails() {
return super.getDetails() + ", Brand: " + brand;
}
// Getter 和 Setter 方法
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
}
子類 NotePad
public class NotePad extends Computer {
private String color;
// 無參構造器
public NotePad() {
super(); // 調用父類的無參構造器
System.out.println("NotePad's no-arg constructor called");
}
// 有參構造器
public NotePad(String cpu, int memory, int storage, String color) {
super(cpu, memory, storage); // 調用父類的有參構造器
this.color = color;
System.out.println("NotePad's parameterized constructor called");
}
// 獲取詳細信息的方法
@Override
public String getDetails() {
return super.getDetails() + ", Color: " + color;
}
// Getter 和 Setter 方法
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
Test 類
public class Test {
public static void main(String[] args) {
// 創(chuàng)建PC對象药磺,使用無參構造器
PC pc1 = new PC();
pc1.setCpu("Intel i7");
pc1.setMemory(16);
pc1.setStorage(512);
pc1.setBrand("Dell");
System.out.println("PC1 Details: " + pc1.getDetails());
// 創(chuàng)建PC對象,使用有參構造器
PC pc2 = new PC("Intel i5", 8, 256, "HP");
System.out.println("PC2 Details: " + pc2.getDetails());
// 創(chuàng)建NotePad對象誉察,使用無參構造器
NotePad notePad1 = new NotePad();
notePad1.setCpu("AMD Ryzen 5");
notePad1.setMemory(8);
notePad1.setStorage(256);
notePad1.setColor("Silver");
System.out.println("NotePad1 Details: " + notePad1.getDetails());
// 創(chuàng)建NotePad對象与涡,使用有參構造器
NotePad notePad2 = new NotePad("AMD Ryzen 7", 16, 512, "Black");
System.out.println("NotePad2 Details: " + notePad2.getDetails());
}
}
7、通過重寫實現(xiàn)編寫一個 Person 類持偏,包括屬性/private(name驼卖、age),構造器鸿秆、方法 say(返回自我介紹的字符串)酌畜。
編寫一個 Student 類,繼承 Person 類卿叽,增加 id桥胞、score 屬性/private,以及構造器考婴,定義 say 方法(返回自我介紹的信息)贩虾。
在 main 中,分別創(chuàng)建 Person 和 Student 對象,調用 say 方法輸出自我介紹
Person 類
public class Person {
// 私有屬性
private String name;
private int age;
// 構造器
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter 和 Setter 方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
// say 方法沥阱,返回自我介紹的字符串
public String say() {
return "Hello, my name is " + name + " and I am " + age + " years old.";
}
}
Student 類
public class Student extends Person {
// 私有屬性
private int id;
private double score;
// 構造器
public Student(String name, int age, int id, double score) {
super(name, age); // 調用父類的構造器
this.id = id;
this.score = score;
}
// Getter 和 Setter 方法
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
// 重寫 say 方法缎罢,返回自我介紹的字符串
@Override
public String say() {
return "Hello, my n
ame is " + getName() + ", I am " + getAge() + " years old, " +
"my student ID is " + id + " and my score is " + score + ".";
}
}
Test 類
public class Test {
public static void main(String[] args) {
// 創(chuàng)建 Person 對象
Person person = new Person("John", 30);
System.out.println(person.say());
// 創(chuàng)建 Student 對象
Student student = new Student("Alice", 20, 12345, 95.5);
System.out.println(student.say());
}
}
8、通過重寫實現(xiàn)編寫一個 Person 類考杉,包括屬性/private(name策精、age),構造器崇棠、方法 say(返回自我介紹的字符串)咽袜。
編寫一個 Student 類,繼承 Person 類枕稀,增加 id询刹、score 屬性/private,以及構造器萎坷,定義 say 方法(返回自我介紹的信息)范抓。
在父類和子類中分別定義一個doing方法父類輸出XXX正在做……,子類輸出XXX正在上課
在 main 中,分別創(chuàng)建 Person 和 Student 對象食铐,調用 say 方法輸出自我介紹
Person 類
public class Person {
// 私有屬性
private String name;
private int age;
// 構造器
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter 和 Setter 方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
// say 方法,返回自我介紹的字符串
public String say() {
return "Hello, my name is " + name + " and I am " + age + " years old.";
}
// doing 方法僧鲁,返回正在做的事情
public void doing() {
System.out.println(name + " is doing something...");
}
}
Student 類
public class Student extends Person {
// 私有屬性
private int id;
private double score;
// 構造器
public Student(String name, int age, int id, double score) {
super(name, age); // 調用父類的構造器
this.id = id;
this.score = score;
}
// Getter 和 Setter 方法
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
// 重寫 say 方法虐呻,返回自我介紹的字符串
@Override
public String say() {
return "Hello, my name is " + getName() + ", I am " + getAge() + " years old, " +
"my student ID is " + id + " and my score is " + score + ".";
}
// 重寫 doing 方法象泵,返回正在上課的信息
@Override
public void doing() {
System.out.println(getName() + " is attending class...");
}
}
Test 類
public class Test {
public static void main(String[] args) {
// 創(chuàng)建 Person 對象
Person person = new Person("John", 30);
System.out.println(person.say());
person.doing();
// 創(chuàng)建 Student 對象
Student student = new Student("Alice", 20, 12345, 95.5);
System.out.println(student.say());
student.doing();
}
}
9、寫程序演示類被加載的情況舉例
1. 創(chuàng)建對象實例時(new)
AA3 aa = new AA3();
2. 創(chuàng)建子類對象實例斟叼,父類也會被加載, 而且偶惠,父類先被加載,子類后被加載
AA3 aa2 = new AA3();
3. 使用類的靜態(tài)成員時(靜態(tài)屬性朗涩,靜態(tài)方法)
System.out.println(Cat.n1);
static代碼塊忽孽,是在類加載時,執(zhí)行的谢床,而且只會執(zhí)行一次.
DD3 dd = new DD3();
DD3 dd1 = new DD3();
普通的代碼塊兄一,在創(chuàng)建對象實例時,會被隱式的調用识腿。
被創(chuàng)建一次出革,就會調用一次。
如果只是使用類的靜態(tài)成員時渡讼,普通代碼塊并不會執(zhí)行
AA3 類
class AA3 {
// 靜態(tài)屬性
static int n1 = initializeStaticVariable();
// 靜態(tài)代碼塊
static {
System.out.println("AA3's static block executed");
}
// 普通代碼塊
{
System.out.println("AA3's instance block executed");
}
// 構造器
public AA3() {
System.out.println("AA3's constructor executed");
}
// 靜態(tài)方法
public static int initializeStaticVariable() {
System.out.println("AA3's static variable initialized");
return 100;
}
}
BB3 類(繼承 AA3)
class BB3 extends AA3 {
// 靜態(tài)代碼塊
static {
System.out.println("BB3's static block executed");
}
// 普通代碼塊
{
System.out.println("BB3's instance block executed");
}
// 構造器
public BB3() {
System.out.println("BB3's constructor executed");
}
}
CC3 類
class CC3 {
// 靜態(tài)屬性
static int n1 = initializeStaticVariable();
// 靜態(tài)代碼塊
static {
System.out.println("CC3's static block executed");
}
// 普通代碼塊
{
System.out.println("CC3's instance block executed");
}
// 構造器
public CC3() {
System.out.println("CC3's constructor executed");
}
// 靜態(tài)方法
public static int initializeStaticVariable() {
System.out.println("CC3's static variable initialized");
return 200;
}
}
DD3 類
class DD3 {
// 靜態(tài)屬性
static int n1 = initializeStaticVariable();
// 靜態(tài)代碼塊
static {
System.out.println("DD3's static block executed");
}
// 普通代碼塊
{
System.out.println("DD3's instance block executed");
}
// 構造器
public DD3() {
System.out.println("DD3's constructor executed");
}
// 靜態(tài)方法
public static int initializeStaticVariable() {
System.out.println("DD3's static variable initialized");
return 300;
}
}
Test 類
public class Test {
public static void main(String[] args) {
// 1. 創(chuàng)建對象實例時(new)
System.out.println("Creating AA3 object:");
AA3 aa = new AA3();
// 2. 創(chuàng)建子類對象實例時骂束,父類也會被加載,父類先被加載成箫,子類后被加載
System.out.println("\nCreating BB3 object:");
BB3 bb = new BB3();
// 3. 使用類的靜態(tài)成員時(靜態(tài)屬性展箱,靜態(tài)方法)
System.out.println("\nAccessing CC3's static member:");
System.out.println("CC3's static variable n1: " + CC3.n1);
// 4. 靜態(tài)代碼塊在類加載時執(zhí)行,并且只會執(zhí)行一次
System.out.println("\nCreating DD3 object:");
DD3 dd = new DD3();
System.out.println("Creating another DD3 object:");
DD3 dd1 = new DD3();
}
}
10蹬昌、寫程序演示類成員的調用順序混驰,(1) A 靜態(tài)代碼塊01 (2) getN1被調用...(3)A 普通代碼塊01(4)getN2被調用...(5)A() 構造器被調用
public class A {
// 靜態(tài)屬性
static int n1 = initializeStaticVariable();
// 靜態(tài)代碼塊01
static {
System.out.println("A's static block 01 executed");
}
// 普通屬性
int n2 = initializeInstanceVariable();
// 普通代碼塊01
{
System.out.println("A's instance block 01 executed");
}
// 構造器
public A() {
System.out.println("A's constructor executed");
}
// 靜態(tài)方法
public static int initializeStaticVariable() {
System.out.println("getN1 method called");
return 100;
}
// 普通方法
public int initializeInstanceVariable() {
System.out.println("getN2 method called");
return 200;
}
public static void main(String[] args) {
System.out.println("Creating A object:");
A a = new A();
}
}
11、編寫程序演示構造器隱含(1)super()(2)調用本類的普通代碼塊
class Parent {
// 父類的普通代碼塊
{
System.out.println("Parent's instance block executed");
}
// 父類的構造器
public Parent() {
System.out.println("Parent's constructor executed");
}
}
public class Child extends Parent {
// 子類的普通代碼塊
{
System.out.println("Child's instance block executed");
}
// 子類的構造器
public Child() {
System.out.println("Child's constructor executed");
}
public static void main(String[] args) {
System.out.println("Creating Child object:");
Child child = new Child();
}
}
13凳厢、通過多態(tài)實現(xiàn)一個動物叫的方法账胧,由于每種動物的叫聲是不同的,因此可以在方法中接收一個動物類型的參數(shù)先紫,當傳入貓類對象時就發(fā)出貓類的叫聲治泥,傳入犬類對象時就發(fā)出犬類的叫聲。
// 動物類
class Animal {
// 叫的方法
public void makeSound() {
System.out.println("動物發(fā)出叫聲");
}
}
// 貓類
class Cat extends Animal {
// 重寫父類的makeSound方法
@Override
public void makeSound() {
System.out.println("貓發(fā)出喵喵的叫聲");
}
}
// 犬類
class Dog extends Animal {
// 重寫父類的makeSound方法
@Override
public void makeSound() {
System.out.println("狗發(fā)出汪汪的叫聲");
}
}
// 測試類
public class Test {
// 叫的方法遮精,接收一個動物類型的參數(shù)
public static void animalSound(Animal animal) {
animal.makeSound(); // 多態(tài)調用
}
public static void main(String[] args) {
// 創(chuàng)建貓和狗對象
Animal cat = new Cat();
Animal dog = new Dog();
// 調用叫的方法居夹,傳入不同的動物對象
System.out.println("傳入貓對象:");
animalSound(cat);
System.out.println("\n傳入狗對象:");
animalSound(dog);
}
}
// 動物類
class Animal {
public void eat() {
System.out.println("動物正在吃東西");
}
}
// 貓類
class Cat extends Animal {
@Override
public void eat() {
System.out.println("貓正在吃魚");
}
public void meow() {
System.out.println("喵喵喵~");
}
}
// 狗類
class Dog extends Animal {
@Override
public void eat() {
System.out.println("狗正在啃骨頭");
}
public void bark() {
System.out.println("汪汪汪~");
}
}
public class Test {
public static void main(String[] args) {
// 向上轉型
Animal animal1 = new Cat(); // 貓向上轉型為動物
Animal animal2 = new Dog(); // 狗向上轉型為動物
// 調用動物類的方法
animal1.eat(); // 輸出:貓正在吃魚
animal2.eat(); // 輸出:狗正在啃骨頭
// 向下轉型
if (animal1 instanceof Cat) {
Cat cat = (Cat) animal1; // 向下轉型為貓
cat.meow(); // 輸出:喵喵喵~
}
if (animal2 instanceof Dog) {
Dog dog = (Dog) animal2; // 向下轉型為狗
dog.bark(); // 輸出:汪汪汪~
}
}
}
16、1)定義一個抽象類Weapon,該抽象類有兩個抽象方法attack()本冲,move()
這兩個方法分別表示武器的攻擊方式和移動方式准脂。
(2)定義3個類:Tank,Flighter,WarShip都繼承自Weapon,
分別用不同的方式實現(xiàn)Weapon類中的抽象方法。
// 抽象類 Weapon
abstract class Weapon {
// 抽象方法 attack檬洞,表示武器的攻擊方式
public abstract void attack();
// 抽象方法 move狸膏,表示武器的移動方式
public abstract void move();
}
// 坦克類,繼承自 Weapon
class Tank extends Weapon {
@Override
public void attack() {
System.out.println("坦克發(fā)射炮彈");
}
@Override
public void move() {
System.out.println("坦克通過履帶移動");
}
}
// 戰(zhàn)斗機類添怔,繼承自 Weapon
class Flighter extends Weapon {
@Override
public void attack() {
System.out.println("戰(zhàn)斗機發(fā)射導彈");
}
@Override
public void move() {
System.out.println("戰(zhàn)斗機通過噴射推進器飛行");
}
}
// 軍艦類湾戳,繼承自 Weapon
class WarShip extends Weapon {
@Override
public void attack() {
System.out.println("軍艦發(fā)射魚雷");
}
@Override
public void move() {
System.out.println("軍艦通過螺旋槳航行");
}
}
// 測試類
public class Test {
public static void main(String[] args) {
// 創(chuàng)建坦克對象
Weapon tank = new Tank();
System.out.println("坦克的攻擊方式和移動方式:");
tank.attack(); // 坦克發(fā)射炮彈
tank.move(); // 坦克通過履帶移動
// 創(chuàng)建戰(zhàn)斗機對象
Weapon flighter = new Flighter();
System.out.println("\n戰(zhàn)斗機的攻擊方式和移動方式:");
flighter.attack(); // 戰(zhàn)斗機發(fā)射導彈
flighter.move(); // 戰(zhàn)斗機通過噴射推進器飛行
// 創(chuàng)建軍艦對象
Weapon warShip = new WarShip();
System.out.println("\n軍艦的攻擊方式和移動方式:");
warShip.attack(); // 軍艦發(fā)射魚雷
warShip.move(); // 軍艦通過螺旋槳航行
}
}
21贤旷、要求輸入對象的年齡在18-120之間,否則拋出一個自定義異常
// 自定義異常類 AgeOutOfRangeException
class AgeOutOfRangeException extends Exception {
public AgeOutOfRangeException(String message) {
super(message);
}
}
// 測試類
public class Test {
// 方法用于驗證年齡是否在合法范圍內
public static void validateAge(int age) throws AgeOutOfRangeException {
if (age < 18 || age > 120) {
throw new AgeOutOfRangeException("年齡必須在18到120之間");
}
}
public static void main(String[] args) {
int age = 15; // 假設輸入的年齡是15歲
try {
// 驗證年齡是否在合法范圍內
validateAge(age);
System.out.println("輸入的年齡合法:" + age);
} catch (AgeOutOfRangeException e) {
System.out.println("輸入的年齡不合法:" + e.getMessage());
}
}
}