【问题标题】:What's wrong with Add() constructor? [duplicate]Add() 构造函数有什么问题? [复制]
【发布时间】:2015-06-18 19:01:56
【问题描述】:

我正在尝试使用多线程添加两个数字,但它在编译时显示以下错误:
" 类中的构造函数 Add 不能应用于给定类型;
类输入扩展添加{
必需:int,int
找到:没有参数
原因:实际参数列表和形式参数列表的长度不同

import java.util.Scanner;

class Add implements Runnable{
    Thread t;
    int a,b,c;
    Add(int a,int b){
        this.a=a;
        this.b=b;
        t = new Thread(this,"add");
        t.start();
    }
    public void run(){
        c=a+b;
        System.out.println("Exiting add thread.");
    }
}
class Input extends Add{
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        Add o = new Add(5,4);
        System.out.println("Enter a string: ");
        String str = sc.nextLine();
        System.out.println("String is : " + str);
        System.out.println("c: " + o.c);
    }
}

【问题讨论】:

标签: java multithreading


【解决方案1】:

由于Add 中唯一可用的构造函数采用两个参数,因此您必须在Input 中有一个显式调用它的构造函数,但您没有。默认的隐式构造函数尝试调用不存在的超类构造函数Add(),因此出现错误。

但是你的Input 类无缘无故地扩展了Add。删除extends Add,它应该可以编译。

class Input {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-29
    • 1970-01-01
    • 2013-10-16
    • 1970-01-01
    • 2017-08-12
    • 1970-01-01
    • 2012-11-28
    相关资源
    最近更新 更多