User Tools

Site Tools


java:initializing_classes_and_constructors

This is an old revision of the document!


Java Constructor Basics

Default constructors

Instance variables have default values. For numbers, the default value is 0, for Booleans it is false, and for object references it is null. However, there will be times when you want to override these default values. For example, let's say we are counting votes for a fraudulent election and want to start our counter at 10,000 without anyone being the wiser. To do this, we will need to use a constructor: a member method that runs automatically whenever you instantiate the object.

Adding a constructor to our class definition that does the nefarious deed mentioned above looks like:

Note the syntax: A constructor does not have a return type, is declared with public access, and has the same name as the class.

So, in short, constructors are used to _initialize_ objects. They can be used for other purposes as well, but object initialization is the main reason they were invented.

Parameterized constructors

toString()

One thing you'll want to get into the habit of doing with your class definitions is to write a toString() method. The method should return a string representation of the object. What you want that representation is up to you. The toString() method will automatically be invoked whenever Java needs a string representation of your object. An example of one for the ClickerCounter class might look like:

public String toString() {
    return "count: " + count;
}

Now if we want to output the state of a counter using System,out.println(), we could simply write:

System.out.println(myCounter);

Writing a toString() instance method is especially important when your class is more complicated than the simple class we've been using here. To understand the magic by which this works, you need to have an understanding of inheritance in Java. But that shouldn't stop you from starting to do this now.

Copyright © 2020 Mithat Konar. All rights reserved.

java/initializing_classes_and_constructors.1599876253.txt.gz · Last modified: 2020/09/12 02:04 by mithat

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki