Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple classes basics, putting a print class into the main method

Tags:

java

oop

I am trying to see the basics for what is required to call in a second class, because tutorials and the book I am using are over-complicating it by using user input right now.

So here is what I tried. First is my main class and the second is the class I tried to call into the main method portraying just a simple text.

public class deck {
    public static void main(String[] args) {
    edward test = new edward();
    System.out.print(test);
    }
}

Other class:

public class edward {
    public void message(int number) {
        System.out.print("hello, this is text!");   
    }
}

How come this doesn't work?

If you could try to explain what I am doing or how this works a bit in detail that would be nice. I'm having a hard time with this part and getting a bit discouraged.

like image 412
Devoted Avatar asked Dec 11 '22 08:12

Devoted


1 Answers

This does not work because you are printing a wrong thing: rather than printing test, you should call a method on it, like this:

public class deck {
    public static void main(String[] args){
        edward test = new edward();
        test.message(123);
    }
}

message(int) is a method (more specifically, an instance method). You call instance methods by specifying an instance on which the method is to be called (in your case, that is test), the name of the method, and its parameters.

The other kind of methods is static - i.e. like main. These methods do not require an instance, but they cannot access instance properties either.

like image 89
Sergey Kalinichenko Avatar answered Dec 13 '22 23:12

Sergey Kalinichenko