Java-未找到合适的构造方法

问题描述 投票:0回答:4

我遇到了编译问题,视频类中没有参数的构造函数。因为我已经明确定义了默认构造函数,所以我不明白该消息,就像编译器看不到它。

确切的错误消息是:

MyMain.java:18: error: no suitable constructor found for Video(no arguments)
        Video v = new Video();
                  ^
    constructor Video.Video(Video) is not applicable
      (actual and formal argument lists differ in length)
    constructor Video.Video(String,int,Support,String[]) is not applicable
      (actual and formal argument lists differ in length)
1 error

这是有问题的课程。

import java.util.Vector;

public class Video {

    public String title;
    public int annee;
    public Support support;
    public Vector<String> acteurs;

    Video(){
        title = "E.T.";
        annee = 1982;
        support = Support.DVD;
        acteurs = new Vector<String>();
        acteurs.add("Drew B.");
    }    
    Video(Video v){
        title = v.title;
        annee = v.annee;
        support = v.support;
    }
    Video(String _title, int _annee, Support _sup, String[] _acteurs){
        title = _title;
        annee = _annee;
        support = _sup;
        acteurs = new Vector<String>();
        for(int i = 0; i < _acteurs.length; i++){
            acteurs.add(_acteurs[i]);
        }

    }
}

还有我的主对象,我在哪里叫构造函数

import td8.Video;
public class MyMain {

    static private void displayVideo(Video v){
        Enumeration enu = v.acteurs.elements();

        System.out.print(v.title+" de "+ v.annee +", avec ");
        while(enu.hasMoreElements()){
            System.out.print(enu.nextElement() + ", ");
        }
        System.out.print("disponible en "+v.support);
    }

    static public void main(String[] args){
        Video v = new Video();
        displayVideo(v);
    }
}
java constructor javac
4个回答
1
投票

尝试将每个构造函数指定为公共Video(...)。如果它们默认为私有或受保护,则可能无法找到它们。

而且,我只见过将方法声明写为public static,而不是相反。它可能有效,但也可以尝试。

祝你好运!


0
投票

您的构造函数是程序包私有的,并且由于您需要将Video类导入到MyMain中,所以这些类在同一程序包中非常[

只需在所有构造函数的前面加上public前缀,即可公开访问它们。

0
投票
由于您的构造函数是默认的而不是公共的,因此在程序包外部将无法访问它。将您的构造函数公开。

0
投票
根据提供的代码,尚不清楚您的类是否与主类位于同一包中,因为缺少包声明。我想该类不在同一个包中。您的构造函数设置为默认值,这就是此行为的原因。

您可以从官方文档(https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html)中获取有关修饰符的更多信息。

根据这些事实,您必须将Video类中的所有构造函数(或仅所需的一个,例如,默认构造函数或复制构造函数...)都更改为public。

import java.util.Vector; public class Video { public String title; public int annee; public Support support; public Vector<String> acteurs; public Video(){ title = "E.T."; annee = 1982; support = Support.DVD; acteurs = new Vector<String>(); acteurs.add("Drew B."); } public Video(Video v){ title = v.title; annee = v.annee; support = v.support; } public Video(String _title, int _annee, Support _sup, String[] _acteurs){ title = _title; annee = _annee; support = _sup; acteurs = new Vector<String>(); for(int i = 0; i < _acteurs.length; i++){ acteurs.add(_acteurs[i]); } } }

© www.soinside.com 2019 - 2024. All rights reserved.