类与对象——对象的组合

xiaoxiao2021-02-28  55

构造方法的快捷键:source->Generator Constructor using filed

长方形类

public class Rectangle { int l; int w; public Rectangle(int l, int w) { this.l = l; this.w = w; } public int area() {//求面积 int area = l*w; return area; } public int zc() {//求周长 int zc = 2*(l+w); return zc; } }

长方体类

public class Cubic { Rectangle rect; int c;//高 //构造方法1 public Cubic() { super(); } //构造方法2 public Cubic(Rectangle rect, int c) { this.rect = rect; this.c = c; } public int v() {// 求体积 return rect.area()*c; } }

测试类

import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Rectangle rect = new Rectangle(2, 3); Cubic c = new Cubic(rect, 4); System.out.println(rect.area()); System.out.println(c.v()); sc.close(); } }
转载请注明原文地址: https://www.6miu.com/read-2624734.html

最新回复(0)