Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Question about methods and constructors

I'm very new to java programming,and have done a bit of python programming in the past (nowhere near proficient, just a beginners course).

Looking more and more into the confusing terms like methods and constructors, I'm wondering... Do they serve basically the same purpose as a function in Python?

Hello Allen C , sorry for the late reply, I am on vacation so this week is pretty much consisting of intense relaxation.

This is a great explanation for you.

So the primary thing you have to understand is that constructors initialize objects which do not currently exist at the given moment, while methods perform operations on the objects that currently exist in the given moment. In short, methods are the functionality of objects that already exist. Take this code for instance

public class Apple {

    //instance variables
    String type; // Macintosh, Green, Red, ...

    /**
     * This is the default constructor that gets called when you use
     * Apple a = new Apple(); which creates an Apple object named a.
     */

    public Apple() {
        // In here you initialize instance variables, and sometimes but rarely
        // do other functionality (at least with basic objects)
        this.type = "macintosh"; // the 'this' keyword refers to 'this' object. so this.type refers to Apple's 'type' instance variable.
    }

    /**
     * This is another constructor with a parameter. You can have more than one
     * constructor as long as they have different parameters. It creates an Apple
     * object when called using Apple a = new Apple("someAppleType");
     */
    public Apple(String t) {
        // when the constructor is called (i.e new Apple() ) this code is executed
        this.type = t;
    }

    /**
     * methods in a class are functions. They are whatever functionality needed
     * for the object
     */
    public String someAppleRelatedMethod(){
        return "hello, Apple class!";
    }

    public static void main(String[] args) {
        // construct an apple
        Apple a = new Apple("green");
        // 'a' is now an Apple object and has all the methods and
        // variables of the Apple class.
        // To use a method from 'a':
        String temp = a.someAppleRelatedMethod();
        System.out.println(temp);
        System.out.println("a's type is " + a.type);
    }
}

I hope that made sense. What the constructor exists for, in its truest essence, is to construct, or create an object of the type of class, and the method is simply supposed to expose the behavior of the object. Some small little differences are that the constructor should not have a return type, whereas the method should have a return type.

Also, as the constructor will always have the same name as the class name, the method may or may not. And where the constructor is implicit, you can guess it — the method is ex$#@*TA.

Pro Tip:  You can always create a new object even without a constructor.  Furthermore, you can use a class without any constructor, because the compiler will add a default constructor, which is empty.

Here is an example....

public class MyClass() {} // <— Super simple class

// And you can create it via new operator
new MyClass();

The general sense of constructors is that they will be called every time when a new object was created, that is sort of the logic behind this tip. YOU SHOULD KNOW THIS, trust me, it is very important.

So freaking helpful. Wish I count upvote and make best answer, but I can't seem to do that for comments! Thanks for taking time off your vacation, hope you can enjoy the rest of it, and thanks again for the perfect answer.

1 Answer

I agree that the comment is the indepth solution, but I thought I'd show you the python equivalents:

Constructors in python:

class Example(object):

    def __init__(self, x):
          #in this case x should be of type integer to be equivalent to the java code
          #you can also rename 'self' to 'this', to make it feel more like java.
          self.x = x

Java equivalent:

public class Example {

    private int x;
    Example(int x){
         //The difference between python is that python explicitly takes a self argument
         this.x = x;
    }
}