7.6实战练习2矩形
尝试编写一个矩形类,讲长与宽作为矩形类的属性,在构造方法中将长、宽初始化,定义一个成员方法求此矩形的面积。
package org.hanqi.pn0120; public class Juxing { Juxing() { chang=15; kuan=10; } double chang; double kuan; void mianji() { System.out.println("mianji="+chang*kuan); } public static void main(String[] args) { Juxing myJuxing=new Juxing(); myJuxing.mianji(); } }
修正:
1 package org.hanqi.pn0120; 2 3 //公共的 4 public class JuXing2 { 5 double chang; 6 double kuan; 7 public JuXing2(double chang,double kuan) 8 { 9 this.chang=chang; 10 this.kuan=kuan; 11 } 12 13 //计算面积 14 double getMianJi() 15 { 16 return this.chang*this.kuan; 17 } 18 19 public static void main(String[] args) 20 { 21 JuXing2 myJX=new JuXing2(20,6); 22 myJX.chang=12; 23 24 System.out.println("长="+myJX.chang); 25 26 System.out.println("矩形的面积="+myJX.getMianJi()); 27 } 28 29 }