public class Main {
public static void main(String[] args) {
// 创建一个 Person 对象
Person person = new Person();
// 设置对象的属性
person.name = "John";
person.age = 25;
person.isMale = true;
// 调用对象的方法
person.eat();
person.sleep();
person.talk("English");
}
}
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
}
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
int sum1 = calculator.add(2, 3);
double sum2 = calculator.add(2.5, 3.5);
int sum3 = calculator.add(2, 3, 4);
System.out.println("Sum 1: " + sum1);
System.out.println("Sum 2: " + sum2);
System.out.println("Sum 3: " + sum3);
}
}
方法重写
方法重写是指在子类中重新定义父类中已经存在的方法,具有相同的名称、参数列表和返回类型。
方法重写允许子类提供对父类方法的新实现,以满足子类的特定需求。
方法重写的特点:
方法名称、参数列表和返回类型必须与父类中的方法相同。
子类方法不能缩小父类方法的访问权限,但可以扩大访问权限。
子类方法不能抛出比父类方法更多的异常,但可以不抛出异常或抛出父类方法抛出的异常的子类异常。
class Animal {
public void makeSound() {
System.out.println("Animal is making a sound.");
}
}
class Dog extends Animal {
public void makeSound() {
System.out.println("Dog is barking.");
}
public void makeSound(String sound) {
System.out.println("Dog is making " + sound + " sound.");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
animal.makeSound(); // Output: Animal is making a sound.
Dog dog = new Dog();
dog.makeSound(); // Output: Dog is barking.
dog.makeSound("woof"); // Output: Dog is making woof sound.
}
}
构造器
package Person;
public class Person {
private String name;
private int age;
private boolean isMale;
// 自定义构造器
public Person(String name, int age, boolean isMale) {
this.name = name;
this.age = age;
this.isMale = isMale;
}
// 无参构造器
public Person() {
// 调用有参构造器,必须放在第一行
this("Tom", 18, true);
}
public static void main(String[] args) {
Person person = new Person("Jerry", 20, false);
System.out.println(person);
Person person1 = new Person();
System.out.println(person1);
}
}