Welcome to the CSC Q&A, where you can get help (and share your knowledge) about computer science!

Instance methods

+8 votes
One of the fill in the blank questions on a practice test mentions instance methods as one that is "attached to a specific object".  I was wondering if anyone could elaborate on this?  And perhaps how said instance methods compare to static methods?
asked Oct 11, 2016 in CSC 211 (F16) by Audrey Hogenkamp (100 points)

3 Answers

+4 votes

length() is an instance method of the String class, so you call it on a specific instance (object) of type String.  For example:  name.length().

On the other hand, sqrt(...) is a static method of the Math class.  There isn't any particular Math object that you're working with -- so you just call it by putting the class name (Math) in front of it.

Similarly, when we create our own methods inside a program, so far we have always made *static* methods, which belong to the program/class as a whole.  They aren't attached to a specific object.  For instance, the gangstaName method we wrote was a static method.  We passed in the String name as a parameter -- gangstaName(s) -- we did NOT call it like:  s.gangstaName(), which we would have done if gangstaName was an instance method inside of the String class.

Some other examples of instance methods include drawOval for Graphics objects, nextLine for Scanner objects, getGraphics for DrawingPanel objects, etc.

Hope that helps...

answered Oct 11, 2016 by Forrest Stonedahl (100 points)
So would our ArtMaker.makeArt be an instance method then?
+3 votes
So an instance method works on an object. For example, if you create a Scanner object called console...

Scanner console = new Scanner(System.in);

and then call say the .next(); method on console, the .next() is an instance method, because console is an instance of the Scanner object. This differs from class methods such as the .pow() method in the Math class because it references an entire java class instead of an object type such as Scanner or String.

The easiest way to tell something is an instance method is if you have to call it on an already declared instance of an object type (such as Scanner or String). If you are referencing a class you don't have in your program, then it probably is not an instance method.

I hope this clarifies at least a little bit of the things you are confused about!
answered Oct 11, 2016 by Brandon Thompson (100 points)
+2 votes
I am a little confused on the instance part too. Looking at the book, it seems the word object and instance sometimes get used interchangeably. Also according to the book, an object is "a programming entity that contains state (data) and behavior (methods)." So I think whenever an object is created, it is an instance of the class it is created in. I hope this helps, but there could be parts that aren't 100% accurate.
answered Oct 11, 2016 by Brandon Wilkerson (100 points)