Chris London Chris London - 12 days ago 5
Java Question

Confused about java constructors

So I am learning

Java
. I am up to
constructors
, and dealing with
classes
. I am having some issues understanding exactly what they do/are for? I believe they are used similar to a function call, passing parameters to a function when called?

Am I correct in this thinking?

So for example:

class test{
void durp(String input){
System.out.print(input);
}
}


If I was to make an object in my main class like this:

test object = new test("hey");


it would pass
hey
as a string to
durp()


Is this correct?

Answer

If I was to make an object in my main class like this: test object = new test("hey"); it would pass "hey" as a string to durp() right?

No, because your method durp() is not the Constructor. It's simply a method belonging to the class and can be called from a created living object.

public class Test {
    /** this is a constructor */
    public Test() {
    } 

    /** this is also a constructor with a parameter */
    public Test(String arg1) { 
        System.out.println(arg1); 
    } 

    /** this is a method of Test */
    public void derp() {
    }
}

You can read this tutorial from oracle about constructors

Comments