【每日代码】(12/21)

本文通过Java代码展示了依赖关系(通过构造函数和方法调用)和关联关系(类之间的数据交互)的实例,包括Phone类与Person类的依赖,以及Goods类与Store类的关联。
摘要由CSDN通过智能技术生成

一段简单的有关四种关系的代码(上)。
如下——

1.依赖关系

package cn.jsu.www10;

import java.util.Scanner;
 
class Phone{
    private String brand;
    public Phone(String brand) {
        this.brand = brand;
    }
    public void call(String name){
        System.out.print("【我用" + this.brand);
        System.out.print("给" + name + "打call】");
    }
}

class Person{
    public Person(Phone phone,String name){
        phone.call(name);
    }
}
public class Yil {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("请输入您的手机品牌:");
        String b = s.next();
        System.out.println("请输入您要拨打的对象:");
        String o = s.next();
        Phone p = new Phone(b);
        Person I = new Person(p,o);
        System.out.println("\n正在拨号中...\n......");
        System.out.println("\n您拨打的电话正忙,请稍后再试。");
    }
}

2.关联关系

package cn.jsu.www10;

class Goods{
    private String name;
    private double price;

    public Goods(String name,double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return this.name;
    }

    public double getPrice() {
        return this.price;
    }

}
class Store{
    private String brand;
    public Store(String brand) {
        this.brand = brand;
    }
    public String getBrand() {
        return this.brand;
    }

    public void sell(String brand,Goods snack){
        System.out.println("欢迎光临" + brand + "!" + "\n本店今日热卖——" + snack.getName() + ",售价:" + snack.getPrice() + "元");
    }
}

public class Guanl {
    public static void main(String[] args) {
        Store store = new Store("【XiaoZのsupermarket】");
        Goods goods = new Goods("可乐", 4);
        store.sell(store.getBrand(),goods);
    }
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值