用值实例化接口类型变量

时间:2020-04-16 15:17:36

标签: java

我当然只做了1小时的接口操作,就把一些任务当做家庭作业了,但这确实给我带来了问题: 接口I1具有:方法:int read();A实现该接口,并包含:从键盘读取值的方法int read(); B类包含:变量c类型I1,构造函数,带有一个用于为c赋值的参数,方法afis()显示{数字。

这是我到目前为止所做的,但是我被困在这里,如何为summ分配一个值并将其与c类中的n1相加?

A

2 个答案:

答案 0 :(得分:0)

看来,您需要在main方法中创建类A的实例,因为它是迄今为止实现接口i1的唯一类:

class B {
    int sum;
    i1 c;

    B(i1 c) {
        this.c = c;
    }
}

class toDo2 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        B n1 = new B(new A());
        // ...
    }
}

此外,类B不会知道其c字段的具体实现-它将能够调用在您的界面中定义的方法int read()

答案 1 :(得分:0)

可以做到

B n1 = new B(new A());

基本上,您的class A类型为I1,因为它正在实现I1

您在这里:

import java.util.Scanner;

public class Main{

     public static void main(String []args){
        I1 a = new A();
        a.read(); //this call will initiate taking input
        B n1 = new B(a);
        int sum = n1.sum(a.getFirstNumber(), a.getSecondNumber());
        System.out.println(sum);
     }
}

interface I1 {
    void read();
    int getFirstNumber();
    int getSecondNumber();
}

class A implements I1 {
    int n1;
    int n2;
    public void read() {
        Scanner in = new Scanner(System.in);
        n1 = in.nextInt();
        n2 = in.nextInt();
    }

    public int getFirstNumber() {
        return n1;
    }

    public int getSecondNumber() {
        return n2;
    }

}

class B {

    I1 c;

    B(I1 c) {
        this.c = c;
    }

    public int sum(int n1, int n2)  {
        return n1+n2;
    }
}