一、今日学习内容
构造函数、析构函数、重载的应用:
1、构造函数
1 public class Rect {
2 private double len,wid;
3 Rect(double l,double w) {
4 len=l;
5 wid=w;
6 }
7 public double area() {
8 return len*wid;
9 }
10
11 public static void main(String[] args) {
12 Rect r=new Rect(3.3,6.1);
13 double a=r.area();
14 System.out.println("面积为:"+a);
15 }
16 }
2、重载函数
1 public class Rect {
2 private double len,wid;
3 Rect(double l,double w) {
4 len=l;
5 wid=w;
6 }
7 Rect(){
8 len=10;
9 wid=5;
10 }
11 public double area() {
12 return len*wid;
13 }
14
15 public static void main(String[] args) {
16 Rect r1=new Rect(3.3,6.1);
17 double a1=r1.area();
18 System.out.println("r1面积为:"+a1);
19 Rect r2=new Rect();
20 double a2=r2.area();
21 System.out.println("r2面积为:"+a2);
22 }
23 }
3、点类(构造函数重载)
1 public class Point2 {
2 private double x,y,z;
3 private int num;
4 Point2(double a,double b,double c,int n){
5 x=a;
6 y=b;
7 z=c;
8 num=n;
9 System.out.println("构造点类:NO."+num);
10 }
11 Point2(double a,double b,int n){
12 x=a;
13 y=b;
14 z=1.0;
15 num=n;
16 System.out.println("构造点类:NO."+num);
17 }
18 Point2(){
19 x=1.0;
20 y=1.0;
21 z=1.0;
22 num=1;
23 System.out.println("构造点类:NO."+num);
24 }
25 public void Output() {
26 System.out.println("点的坐标为:("+x+","+y+","+z+")");
27 }
28 public static void main(String[] args) {
29 Point2[] p=new Point2[3];
30 p[0]=new Point2();
31 p[1]=new Point2(1.0,2.0,3.0,2);
32 p[2]=new Point2(6.0,2.0,3);
33 for(int i=0;i<3;i++) {
34 p[i].Output();
35 }
36 }
37 }
4、交通工具类
设计一个交通工具类Vehicle,包含当前载重量和最大载重量两个私有属性,要求具有以下功能和内容:有两个构造函数(其中一个为默认构造函数);可分别设置两个属性的值;可判断当前载重量是否符合最大载重量以及加入一定重量后是否超载,若超载发出报警信息。
1 import java.util.Scanner;
2 public class Vehicle {
3 private double preh,maxh;
4 Vehicle(){
5 System.out.println("请输入相关数据(当前重量、最大承载重量):");
6 Scanner con=new Scanner(System.in);
7 preh=con.nextDouble();
8 maxh=con.nextDouble();
9 }
10 Vehicle(double p,double m){
11 preh=p;
12 maxh=m;
13 }
14 public void display() {
15 Scanner con=new Scanner(System.in);
16 if(preh>maxh)System.out.println("当前质量超过最大重量,超重!");
17 else {
18 System.out.println("请输入再次加入的重量:");
19 double a=con.nextDouble();
20 if((preh+a)>maxh)System.out.println("再次加入后超重!");
21 else System.out.println("再次加入后没有超重!");
22 }
23 }
24
25 public static void main(String[] args) {
26 Vehicle v1=new Vehicle();
27 Vehicle v2=new Vehicle(300,500);
28 System.out.println("v1的当前重量为:"+v1.preh+"\t v1的最大承载重量为:"+v1.maxh);
29 v1.display();
30 System.out.println("v2的当前重量为:"+v2.preh+"\t v2的最大承载重量为:"+v2.maxh);
31 v2.display();
32 }
33 }
二、遇到的问题
对Java中类的构造函数、析构函数不清楚,导致函数不会运用。
三、明日计划
继续完成例题的验证。

浙公网安备 33010602011771号