实验二 Java简单类与对象
(1) 使用构造函数完成各属性的初始赋值。
(2) 使用get…()和set…()的形式完成属性的访问及修改。
(3) 提供计算面积的getArea()方法和计算周长的getLength()方法。
1.实验代码
public class Rectangle { public static void main(String args[]) { Rectangle rec=new Rectangle(); rec.setWidth(3); rec.setHeight(4); rec.setColor("红色"); rec.getArea(); rec.getLength(); System.out.println("长:"+rec.getWidth()+"\n高:"+rec.getHeight()+"\n颜色:"+rec.getColor()); } double width,height; String color="red"; public double getHeight() { return height; } public double getWidth() { return width; } public String getColor() { return color; } public void setHeight(double height) { this.height = height; } public void setWidth(double width) { this.width = width; } public void setColor(String color) { this.color = color; } public void getArea() { double area=0; area=this.height*this.width; System.out.println("面积为"+area); } public void getLength() { double length=0; length=(this.height+this.width)*2; System.out.println("周长为"+length); } }
实验结果
学习总结
这周学习了string类以及它的一些常用方法,其中细讲了string对象的内容比较与string的类的两种实例化方式的区别;
虽然上课听起来不是那么难,但自己操作起来感觉还是不怎么会,实践能力还是不行,需多加练习。
原文:https://www.cnblogs.com/liuz98/p/11558925.html