Java期末復習

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());
        }
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末砾脑,一起剝皮案震驚了整個濱河市幼驶,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌韧衣,老刑警劉巖盅藻,帶你破解...
    沈念sama閱讀 217,657評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異畅铭,居然都是意外死亡氏淑,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評論 3 394
  • 文/潘曉璐 我一進店門顶瞒,熙熙樓的掌柜王于貴愁眉苦臉地迎上來夸政,“玉大人,你說我怎么就攤上這事榴徐∈匚剩” “怎么了?”我有些...
    開封第一講書人閱讀 164,057評論 0 354
  • 文/不壞的土叔 我叫張陵坑资,是天一觀的道長耗帕。 經常有香客問我,道長袱贮,這世上最難降的妖魔是什么仿便? 我笑而不...
    開封第一講書人閱讀 58,509評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮攒巍,結果婚禮上嗽仪,老公的妹妹穿的比我還像新娘婉称。我一直安慰自己题画,他們只是感情好,可當我...
    茶點故事閱讀 67,562評論 6 392
  • 文/花漫 我一把揭開白布逝她。 她就那樣靜靜地躺著兢孝,像睡著了一般窿凤。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上跨蟹,一...
    開封第一講書人閱讀 51,443評論 1 302
  • 那天雳殊,我揣著相機與錄音,去河邊找鬼窗轩。 笑死夯秃,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播寝并,決...
    沈念sama閱讀 40,251評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼箫措,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了衬潦?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,129評論 0 276
  • 序言:老撾萬榮一對情侶失蹤植酥,失蹤者是張志新(化名)和其女友劉穎镀岛,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體友驮,經...
    沈念sama閱讀 45,561評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡漂羊,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,779評論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了卸留。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片走越。...
    茶點故事閱讀 39,902評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖耻瑟,靈堂內的尸體忽然破棺而出旨指,到底是詐尸還是另有隱情,我是刑警寧澤喳整,帶...
    沈念sama閱讀 35,621評論 5 345
  • 正文 年R本政府宣布谆构,位于F島的核電站,受9級特大地震影響框都,放射性物質發(fā)生泄漏搬素。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,220評論 3 328
  • 文/蒙蒙 一魏保、第九天 我趴在偏房一處隱蔽的房頂上張望熬尺。 院中可真熱鬧,春花似錦谓罗、人聲如沸粱哼。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽皂吮。三九已至,卻和暖如春税手,著一層夾襖步出監(jiān)牢的瞬間蜂筹,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評論 1 269
  • 我被黑心中介騙來泰國打工芦倒, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留艺挪,地道東北人。 一個月前我還...
    沈念sama閱讀 48,025評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像麻裳,于是被迫代替她去往敵國和親口蝠。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,843評論 2 354

推薦閱讀更多精彩內容

  • 1. Java基礎部分 基礎部分的順序:基本語法津坑,類相關的語法妙蔗,內部類的語法,繼承相關的語法疆瑰,異常的語法眉反,線程的語...
    子非魚_t_閱讀 31,631評論 18 399
  • 1、類 創(chuàng)建類 public class Computer { //修飾符public:類可以被任意訪問 //類的...
    小短腿要早睡啊閱讀 450評論 0 0
  • 原創(chuàng)者:文思 一穆役、設計原則 設計模式的目的:代碼重用性寸五、可讀性、維護性...
    文思li閱讀 374評論 0 0
  • 一耿币、抽象類與抽象方法 1.抽象類定義: 隨著繼承層次中一個個新子類的定義梳杏,類變得越來越具體,而父類則更一般淹接,更通用...
    不差不多閱讀 246評論 0 0
  • 一. Java基礎部分.................................................
    wy_sure閱讀 3,811評論 0 11