第二次过程性考核
码云仓库的地址:https://gitee.com/zyr16012001/codes
第一题:学生类 - 构造函数
题意:定义一个有关学生的Student类,内含类成员变量: String name、String sex、int age,所有的变量必须为私有(private)。
1.编写有参构造函数:
能对name,sex,age赋值。
2.覆盖 to String 函数:
按照格式:类名 [name=, sex=, age=]输出。使用idea自动生成,然后在修改成该输出格式
3.在main中:
输入1行name age sex , 调用上面的有参构造函数新建对象。
4.输出样式:
tom 15 male
Student [name='tom', sex='male', age=15]
程序设计思路:根据题意可知,先定义Student类,定义Student的构造方法,定义toString方法,并按照格式输出类名 [name=, sex=, age=]输出,再使用idea自动生成,然后在修改成该输出格式,最后创建主类Main函数,调用上面的有参构造函数新建对象。
import java.util.Scanner; class Student { private String name; private String sex; private int age; public Student() { this.name = "tom"; this.sex = "male"; this.age = 15; } public void toString(String n, int a, String s) { this.name = n; this.sex = s; this.age = a; System.out.println("Student [name='" + this.name + "', sex='" + this.sex + "', age=" + this.age + "]"); } } public class StudentClass { public static void main(String[] args) { Scanner reader = new Scanner(System.in);
String n = reader.next(); int a = reader.nextInt(); String s = reader.next(); Student ww = new Student(); ww.toString(n, a, s); reader.close(); } }
使用到的知识点:类与对象、子类与继承的综合使用
运行结果:

第二题:定义类
程序设计思路:根据题意可知,将类class RR补全。首先先定义RR类,然后定义方法fun(int a, int b,int c,int d,int e),并且编写平均数式子,最后在return z 返回值
代码片段:
class RR { double z; public double fun(int a, int b, int c, int d, int e) { z = (a + b + c + d + e) / 5; return z; } }
使用到的知识点:参数传值,类的定义
运行结果:

第三题:横平竖直
程序设计思路:根据题意可知:如果高度大于宽度,则输出A,否则输出B;结果返回 return 0。
代码片段:
public char status(double rate) { System.out.println("B"); return 0; } public char status(int rate) { System.out.println("A"); return 0; }
使用到的知识点:方法重载 ,参数传值
运行结果:

第四题:程序改错题
程序设计思路:因为Animal是Dog的上转型对象,即不能操作子类新增的成员变量,也不能调用子类新增的方法;可以将对象的上转型对象再强制转换到一个子类对象,这时,该子类对象又具备了子类所有的属性和功能。(eclipse检测错误)
代码片段:
public class Main { 2 public static void main(String[] args) { 3 Animal animal = new Dog(); 4 animal.shout(); 5 ((Dog) animal).run(); 6 } 7 } 8 9 class Animal { 10 void shout() { 11 System.out.println("animal shout!"); 12 } 13 } 14 15 class Dog extends Animal { 16 void shout() { 17 super.shout(); 18 System.out.println("wangwang……"); 19 } 20 21 void run() { 22 System.out.println("Dog is running"); 23 } 24 }
使用到的知识点:子类的继承性,对象的上转型对象
运行结果:

| 新学内容 | 代码行数 | 博客 |
| 类与对象 ,子类与继承 | 600 | 500 |
浙公网安备 33010602011771号