• 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.定义静态变量nfn1()中对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.定义BoatCat两个类,二者都有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 }

  • 相关阅读:
    HDOJ 1220 Cube
    LCIS(m*n) 最长公共上升子序列
    第二百九十七天 how can I 坚持
    第二百九十六天 how can I 坚持
    第二百九十五天 how can i 坚持
    第二百九十四天 how can I 坚持
    第二百九十三天 how can I 坚持
    第二百九十、一、二天 how can I 坚持
    第二百八十九天 how can I 坚持
    第二百八十八天 how can I坚持
  • 原文地址:https://www.cnblogs.com/znjy/p/13574249.html
Copyright © 2020-2023  润新知