homerun
homerun

Reputation: 20775

trying to work classes together

I'm looking into learning java and i have a little problem with the code.

so i have this class called apples defining 3 strings

public class apples {

    public static String a,b,c;

    public static void main(String[] args){
        a = "its an a";
        b = "its an b";
        c = "its an c";

    }
    public void printit(){
        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
    }

}

and then i have this classed callled workingWith2NDclass which should be working along with the apples class

public class workingWith2NDclass {
    public static void main(){
        apples aMethod = new apples();
        aMethod.printit();
    }
}

what i'm trying to do is to see how class works together but somewhat the line that calls the printit function wont work, why is that?

Upvotes: 0

Views: 65

Answers (2)

Jake
Jake

Reputation: 407

Unfortunately, I don't have the rep to comment on a sub-post, but you have an error here:

public class workingWith2NDclass {
    public static void main(){
        apples aMethod = new apples();
        aMethod.printit();
    }
}

You should have 'String[] args' as an argument in the entry method. These are the args specified when your program is started via the command line.

public class workingWith2NDclass {
    public static void main(String[] args){
        apples aMethod = new apples();
        aMethod.printit();
    }
}

Upvotes: 1

user798182
user798182

Reputation:

The main method in workingWith2NDclass does not call the main method in the apples class. Because of this, when the printit() method is called, a, b, and c are not initialized (i.e. they have no value).

I think what you want is to use a contructor method as follows:

public class apples {
    public static String a,b,c;
    // This method contructs the appls class, to be used by others. It initializes the a, b, and c members.
    public apples(){
        a = "its an a";
        b = "its an b";
        c = "its an c";
    }
    public void printit(){
        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
    }
}

When you run a java program, only one main method (that of the entry class) is called. That means that, because apples does not have a main method, you have to call the one in workingWith2NDclass.

So you now compile your program as

javac workingWith2NDclass.java

and run it with

java workingWith2NDclass

Upvotes: 1

Related Questions