• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
戈瑾
博客园    首页    新随笔    联系   管理    订阅  订阅
Java入门——day53
实验题

1.Cat类

定义一个Cat类,拥有静态数据成员numOfCats,记录Cat的个体数目;静态成员函数getNumOfCats(),读取numOfCats。设计程序测试这个类,体会静态数据成员和静态成员函数的用法。

 1 //Cat类
 2 public class Cat {
 3     private static int numOfCats=0; //记录Cat的个体数目
 4     Cat(){
 5         numOfCats++;
 6     }
 7     public static int getNumOfCats() {
 8         return numOfCats;
 9     }
10     public static void main(String[] args) {
11         int n=6;
12         Cat cat[]=new Cat[n];
13         for(int i=0;i<n;i++) {
14             cat[i]=new Cat();
15             System.out.println("There are "+Cat.getNumOfCats()+" cat.");
16         }
17     }
18 }


 

 2.定义静态变量n,fn1()中对n值加1,在主函数中,加十次,显示n的值。

 1 package com.practice;
 2 public class Test {
 3     public static int n=0;
 4     public static void main(String[] args) {
 5         for(int i=0;i<10;i++) {
 6             n++;
 7             System.out.println("n的值为:"+n);
 8         }
 9     }
10 }

 


 

 

3.定义Boat和Cat两个类,二者都有weight属性,定义函数getTotalWeight(),计算二者的重量和。

 

 1 //Boat类
 2 class Boat{
 3     private double weight; //重量
 4     Boat(){
 5     }
 6     public Boat(double weight) {
 7         this.weight = weight;
 8     }
 9     public double getWeight() {
10         return weight;
11     }
12     public void setWeight(double weight) {
13         this.weight = weight;
14     }
15 }
16 //Cat类
17 class Cat{
18     private double weight; //重量
19     public Cat() {
20     }
21     public Cat(double weight) {
22         this.weight = weight;
23     }
24     public double getTotalWeight(Boat b) {
25         return weight+b.getWeight();
26     }
27     public double getWeight() {
28         return weight;
29     }
30     public void setWeight(double weight) {
31         this.weight = weight;
32     }
33 }
34 public class Test {
35     public static void main(String[] args) {
36         Boat b=new Boat(8);
37         Cat c=new Cat(5);
38         System.out.println("Boat重量:"+b.getWeight());
39         System.out.println("Cat重量:"+c.getWeight());
40         System.out.println("重量之和:"+c.getTotalWeight(b));
41     }
42 }

 

 

posted on 2020-08-27 21:57  戈瑾  阅读(228)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3