Java error 'constructor' X in class 'X' can not be applied to given types; "

2

When compiling the code below I get the following error:

Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: Connection.ConnectionMySQL.<init>

And in line public class DAOusuario extends ConnectionMySQL { shows this in the "tip":

constructor ConnectionMySQL in class ConnectionMySQL cannot be applied to given types;
required: String, String, String, String

found: no arguments

reason: actual and formal arguments list differ in lenght

I think it's some incompatibility with the code being int and the name, email, and password are String . But I could not figure out how to fix the error.

package Usuario;

import Connection.ConnectionMySQL;
import Modelo.ModeloUsuario;


/**
 *
 * @author 02799485227
 */
public class DAOusuario extends ConnectionMySQL {



       // grava o usuário

     public int salvarUsuario(ModeloUsuario pModelUsuario){
        try {
            this.conectar();
                return this.insertSQL(
                "INSERT INTO usuario("
                    + "nome,"
                    + "email,"
                    + "senha"
                + ") VALUES ("
                    + "'" + pModelUsuario.getNome() + "',"
                    + "'" + pModelUsuario.getEmail() + "',"
                    + "'" + pModelUsuario.getSenha() + "'"
                + ");"
            );
        }catch(Exception e){
            e.printStackTrace();
            return 0;
        }finally{
            this.fecharConexao();
        }
  }//Recupera DAOusuario
  public ModeloUsuario getUsuario(int pCodigo){
      ModeloUsuario modeloUsuario = new ModeloUsuario();
      try{
          this.conectar();
          this.executarSQL(
                    "SELECT "
                        + "codigo,"
                        + "nome,"
                        + "email,"
                        + "senha"
                    + "FROM"
                        + "usuario"
                    + "WHERE"
                        + "codigo= '" + pCodigo +"'"
                     +";"
          );
          while(this.getResultSet().next()){
                modeloUsuario.setCodigo(this.getResultSet().getInt(1));
                modeloUsuario.setNome(this.getResultSet().getString("admin"));
                modeloUsuario.setEmail(this.getResultSet().getString("admin"));
                modeloUsuario.setSenha(this.getResultSet().getString("admin"));
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            this.fecharConexao();
        }
        return modeloUsuario;
      }


    // código para login
   public ModeloUsuario getUsuario(String pEmail){
      ModeloUsuario modelUsuario = new ModeloUsuario();
        try {
            this.conectar();
            this.executarSQL(
                "SELECT "
                    + "codigo,"
                    + "nome,"
                    + "email,"
                    + "senha"
                 + " FROM"
                     + " usuario"
                 + " WHERE"
                     + " email = '" + pEmail + "'"
                + ";"
            );

            while(this.getResultSet().next()){
                modelUsuario.setCodigo(this.getResultSet().getInt(1));
                modelUsuario.setNome(this.getResultSet().getString(2));
                modelUsuario.setEmail(this.getResultSet().getString(3));
                modelUsuario.setSenha(this.getResultSet().getString(4));
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            this.fecharConexao();
        }
        return modelUsuario;
    }



   public boolean getUsuario(ModeloUsuario pModelUsuario){       
        try {
            this.conectar();
            this.executarSQL(
                    "SELECT "
                    + "codigo,"
                    + "email,"
                    + "senha"
                    + " FROM"
                    + "usuario"
                    + " WHERE"
                    + " email = '" + pModelUsuario.getEmail()+ "' AND senha = '" + pModelUsuario.getSenha() + "' "
                    + ";"
            );

            if (getResultSet().next()) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            this.fecharConexao();
        }      
    }
}

ConnectionMySQL class

package Connection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;

/**
 *
 * @author 02799485227
 */
public class ConnectionMySQL {
    public Connection con = null; // Conexão a aplicação ao Banco de Dados
    private boolean status = false;
    private String msg = ""; //Informar o status da conexão
    private Statement stmt; //Executa o comando SQL do driver
    private ResultSet resultSet; //Consultar a Base de Dados

    //Variáveis de conexão ao servidor de Banco de Dados
    private String servidor = "localhost";
    private String banco = "sisacai";
    private String usuario = "root";
    private String senha = "root";

    public ConnectionMySQL(String pServidor, String pBanco, String pUsuario, String pSenha){
        this.servidor = pServidor;
        this.banco = pBanco;
        this.usuario = pUsuario;
        this.senha = pSenha;
    }



    public Connection conectar() throws InstantiationException, IllegalAccessException, SQLException{
        try{
            Class.forName("com.mysql.jdbc.Driver").newInstance();

            //local do banco, nome do banco, usuátio e senha
            String url = "jdbc:mysql://" + servidor + "/" + banco;
            this.setCon((Connection)DriverManager.getConnection(url, usuario, senha));
            this.status = true;
        }

        catch(ClassNotFoundException e){
            JOptionPane.showMessageDialog(null,e.getMessage());
        }
        return this.getCon();
    } 

    //dc executa consultas SQL
    public boolean executarSQL(String pSQL){
        try{
            this.setStmt((Statement)getCon().createStatement());
            this.setResultSet(getStmt().executeQuery(pSQL));
        }

        catch (SQLException ex){
            ex.printStackTrace();
            return false;
        }
        return true;
    }
    // Executa Insert SQL
    public int insertSQL(String pSQL){
        int status = 0;
        try{
            //create Statement de con para criar o Statement
            this.setStmt((Statement)getCon().createStatement());

            //Definido o Statement, executamos a query no banco de dados
            this.getStmt().executeUpdate(pSQL);

            //Consulta o último id inserido
            this.setResultSet(this.getStmt().executeQuery("SELECT last_insert_id();"));

            //Recupera o último id inserido
            while(this.resultSet.next()){
                status = this.resultSet.getInt(1);
            }
            //Retorna o último id inserido
            return status;
        }

        catch(SQLException ex){
            ex.printStackTrace();
            return status;
        }
    }

    //Encerra a concexão corrente
     public boolean fecharConexao(){
         try{
             if((this.getResultSet() != null) && (this.stmt != null)){
                 this.getResultSet().close();
                 this.stmt.close();
             }
             this.getCon().close();
             return true;
         }
         catch(SQLException e){
             JOptionPane.showMessageDialog(null,e.getMessage());
         }
         return false;
     }

     //Métodos de seleção e modificação
     public Statement getStmt(){
         return stmt;
     }

     public void setStmt(Statement stmt){
         this.stmt = stmt;
     }

     public ResultSet getResultSet(){
         return resultSet;
     }

     public void setResultSet(ResultSet resultSet){
         this.resultSet = resultSet;
     }

     public Connection getCon(){
         return con;
     }

     public void setCon(Connection con){
         this.con = con;
     }

     public void setMensagem(String mensagem){
         this.msg = mensagem;
     }

     public String getMensagem(){
         return msg;
     }

     public boolean isStatus(){
         return this.status;
     }

     public String getServidor(){
         return servidor;
     }

     public void setServidor(String servidor){
         this.servidor = servidor;
     }

     public String getNomeDoBanco(){
         return banco;
     }

     public void setNomeDoBanco(String nomeDoBanco){
         this.banco = nomeDoBanco;
     }

     public String getUsuario(){
         return usuario;
     }

     public void setUsuario(String usuario){
         this.usuario = usuario;
     }

     public String getSenha(){
         return senha;
     }

     public void setSenha(String senha){
         this.senha = senha;
     }
}
    
asked by anonymous 12.11.2018 / 02:39

1 answer

3

The error is because its class DAOusuario (daughter-class) is inheriting from ConnectionMySQL (parent-class), which has a parameterized constructor, but in the child class, you start it but do not pass the parameters which the parent class expects to be instantiated. You need to pass these values still in the child class constructor to the parent class, using super() , which would look something like this:

public DAOusuario() {

super(//aqui você passa os valores esperados no construtor de ConnectionMySQL);

}

However, this does not make much sense in this code since the values appear to be in the ConnectionMySQL class, not the one that inherited it. For me there is a misuse of the concept here, it does not make sense for these classes to have an inheritance relationship, the ConnectionMySQL class seems self-sufficient to work, the most appropriate relationship here may be composition and not inheritance.     

12.11.2018 / 03:01