zoukankan      html  css  js  c++  java
  • 第四周课程总结&试验报告(二)

    实验二 Java简单类与对象

    实验目的
    掌握类的定义,熟悉属性、构造函数、方法的作用,掌握用类作为类型声明变量和方法返回值;
    理解类和对象的区别,掌握构造函数的使用,熟悉通过对象名引用实例的方法和属性;
    理解static修饰付对类、类成员变量及类方法的影响。
    实验内容
    写一个名为Rectangle的类表示矩形。其属性包括宽width、高height和颜色color,width和height都是double型的,而color则是String类型的。要求该类具有:
    (1) 使用构造函数完成各属性的初始赋值

    (2) 使用get…()和set…()的形式完成属性的访问及修改

    (3) 提供计算面积的getArea()方法和计算周长的getLength()方法
    1.实验代码

    import java.util.Scanner;
    public class Rectangle{
        private double width;
        private double height;
        private String color;
        public double getHeight() {
            return height;
        }
        public void setHeight(double height) {
            this.height = height;
        }
        public double getWidth() {
            return width;
        }
        public void setWidth(double width) {
            this.width = width;
        }
        public String getColor() {
            return color;
        }
        public void setColor(String color) {
            this.color = color;
        }
        public Rectangle(double width,double height,String color){
            this.setColor(color);
            this.setHeight(height);
            this.setWidth(width);
        }
        
        public void getArea(){
            double area=0;
            area=this.height*this.width;
            System.out.println("矩形的面积为"+area);
        }
        public void getGirth() {
            double girth=0;
            girth=(this.height+this.width)*2;
            System.out.println("矩形的周长为"+girth); 
        }
        public String toString(){
            String Str="矩形的高度:"+this.getHeight()+" 宽度:"+this.getWidth()
            +" 颜色:"+this.getColor();
            return Str;
        }
        public static void main(String[] args) {
        
            Rectangle a=new Rectangle(3, 4, "黑色");
            a.getArea();
            a.getGirth();
            System.out.println(a.toString());
            }
    }
    

    2.实验截图

  • 相关阅读:
    [算法]最长的可整合数组的长度
    [算法]在行列都排好序的矩阵中找数
    [算法]在数组中找到出现次数大于N/K的数
    [算法]需要排序的最短子数组长度
    [算法]找到无序数组中最小的K个数
    [算法]“之”字形打印矩阵
    [java]final关键字、finally关键字与finalize()方法
    [算法]旋转矩阵问题(Spiral Matrix)
    [算法]位运算问题之三(实现加减乘除)
    [IDE]Intellij Idea学习整理
  • 原文地址:https://www.cnblogs.com/wmf0616/p/11560123.html
Copyright © 2011-2022 走看看