定义一个矩形类Rectangle:(知识点:对象的创建和使用)
1 定义三个方法:getArea()求面积、getPer()求周长,showAll()分别在控制台输出长、宽、面积、周长。
2 有2个属性:长length、宽width
3 创建一个Rectangle对象,并输出相关信息
1 package shuzudy; 2 3 public class Texta { 4 // 1 定义三个方法:getArea()求面积、getPer()求周长,showAll()分别在控制台输出长、宽、面积、周长 5 int length; 6 int width; 7 8 public void getArea(){ 9 System.out.println("面积是"+length*width); 10 } 11 public void getPer(){ 12 System.out.println("周长是"+(length+width)*2); 13 } 14 public void showAll(){ 15 System.out.println("长是"+length); 16 System.out.println("宽是"+width); 17 System.out.println("面积是"+length*width); 18 System.out.println("周长是"+(length+width)*2); 19 20 } 21 22 }
1 package shuzudy; 2 3 public class Textb { 4 5 public static void main(String[] args) { 6 // 创建一个Rectangle对象,并输出相关信息 7 Texta Rectangle=new Texta(); 8 Rectangle.length =5; 9 Rectangle.width =6; 10 Rectangle.getArea(); 11 Rectangle.getPer(); 12 Rectangle.showAll(); 13 14 15 } 16 17 }
面积是30
周长是22
长是5
宽是6
面积是30
周长是22