0

I'm just learning OOP in Java. I'm trying to call a constructor from another one to enter a message. Thank you for your help. Here's my code:

import java.util.Scanner;

class Sample {
    private String User;
    private int ID;

    public Sample(String user) {
        Scanner sc = new Scanner(System.in);
        User = user;
        ID = 0;
        User = sc.nextLine();
        ID = sc.nextInt();
    }//CONSTRUCTOR

}//Sample

public class Sample_2 {
    private Sample user1, user2, user3;

    public Sample_2() {
        user1 = new Sample();   //FROM HERE I WANT TO CALL THE OTHER CONSTRUCTOR ABOVE.
        user2 = new Sample();
        user3 = new Sample();
    }//CONSTRUCTOR

    public static void main(String args[]){

    }//main

}//Sample_2
0

1 Answer 1

2

There's no default constructor (i.e. with no arguments) for Sample so you need either to add one, like this:

class Sample{

    private String User;
    private int ID;

    public Sample() {
        /* something */
    }

    public Sample(String user){
        // ...

or to use the one with a String parameter, like this:

public Sample_2(){
   user1 = new Sample("some string"); 
   // ...

For some reading, see this tutorial on constructors

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.