简体   繁体   中英

Is this thing a method(java)?

Still in the early stages of learning Java and I saw the following in some code which I did not understand:

public class sprite {
     private Image image;

     public Sprite(Image image) {
          this.image = image;
     }

I'm not asking for an explanation of what the code is doing, I'm just curious what "public Sprite(..." is. Is it some kind of method? It doesn't declare a return type and it's not void.

Thanks for any responses. An actually explaination of what the code is really doing might be over my head I just want to know about the language construct.

Assuming you have a typo (ie assuming the first line is actually public class Sprite { ), then that is a constructor . It's used to initialise an object of type Sprite , so it doesn't return anything, so it's not a method.

It's invoked when you do something like:

Image image = ...;
Sprite s = new Sprite(image);  // Constructor called here

[If you don't have a typo, then it's not a constructor, it's simply invalid Java.]

In java, a class method which doesn't declare a return type and carries the same name as the class is known as a constructor. It is the method that gets called when you make a new object.

public class Foo {
    private int bar;
    public Foo(int arg) {
        this.bar = arg;
    }
}

Foo f = new Foo(1);

would make a new instance of Foo and set it's internal variable bar to 1

It's a constructor. It is a special method that instantiates an object of the class; typically it will set values, initialize any internal objects its uses. You can have multiple constructors, with different signature, for a class.

In this case, the constructor is public, and initializes the object's image property to the image passed to the constructor.

For more, see this documentation .

That's a constructor.

It allows you to create an instance of the Sprite class from a parameter.

This is called a constructor. This is not a method.

More explanations here: http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html . And good luck ;)

public Sprite(Image image) is a constructor for the class Sprite . It does any setup that might need to be done any time an instance of the class is created (like when you use the 'new' keyword), in this case, setting the image instance variable to the one passed by the caller in the constructor.

It's a constructor. Note,that you should capitalize first letter of class Sprite

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM