这些都是从开始学习Java的时候一些练习题(收录在这里以便于自己复习)
方法的重写
- 编写一个Person类,包括属性name(public),age(private),构造器、方法getInfo(返回自己的信息)。
- 编写一个Student类,继承Person类,增加ID(private)、Score(private),静态变量School,以及构造器,定义getInfo方法(返回自己的信息)。
- 编写Test类:
- 分别创建Person和Student对象,调用getInfo方法输出自我介绍。
- 创建两个学生对象,输出静态变量,修改其中某一个对象的静态变量,再次输出进行比较
- 重写Student类的toString方法
class Person {
public String name;
private int age;
public Person(String name, int age){
this.name = name;
this.age = age;
}
public String getInfo(){
return "person: name:" + name +"age:"+ age;
}
}
class Student extends Person{
private int ID;
private int score;
private static String school = "宇宙第一中学";
public Student(String name, int age, int ID, int score) {
super(name,age);
this.ID = ID;
this.score = score;
}
public void Setschool(String school){
this.school = school;
}
public String getInfo(){
return "student:ID: " +ID+"score:"+score+"school:"+school;
}
public String toString(){
return "Student{ID=1001, Score=123}";
}
}
public class java_test5 {
public static void main(String[]args) {
Person person = new Person("张三", 18);
Student student1 = new Student("李四", 17, 1001, 83);
System.out.println(person.getInfo());
System.out.println(student1.getInfo());
Student student2 = new Student("王五", 18, 1002, 90);
student1.Setschool("改名后的中学");
System.out.println(person.getInfo());
System.out.println(student2.getInfo());
System.out.println(person.toString());
System.out.println(student1.toString());
}
}
方法的重载
编程:设计一个乘法类Multiplication,在其中定义三个同名的mul方法:第一个方法是计算两个整数的积;第二个方法是计算两个浮点数的积;第三个方法是计算三个浮点数的积。然后定义测试程序调用这三个同名的方法mul,输出其测试结果。
class Multiplication{
public int mul(int a, int b){
return a*b;
}
public double mul(double a, double b){
return a*b;
}
public double mul(double a, double b, double c){
return a*b*c;
}
}
public class java_test4 {
public static void main(String[]args){
int result;
double result_f;
Multiplication test = new Multiplication();
result = test.mul(8,8);
System.out.println("计算整数的积:"+result);
result_f = test.mul(6.5,3.2);
System.out.println("计算浮点数的积:"+result_f);
result_f = test.mul(2.0,3.0,6.0);
System.out.println("计算三个浮点数的积:"+result_f);
}
}