User Tools

Site Tools


java:initializing_classes_and_constructors

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
Next revisionBoth sides next revision
java:constructor_basics [2020/09/12 04:36] – [Java Constructor Basics] mithatjava:constructor_basics [2020/09/12 04:58] – [Default constructors] mithat
Line 1: Line 1:
 ======  Initializing Classes and Constructors ======  ======  Initializing Classes and Constructors ====== 
  
-===== Default constructors =====+===== Initializing member variables =====
  
-Instance variables have default values. For numbers, the default value is 0, for Booleans it is false, and for object references it is null.+Member variables will be given default values on instantiation. 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 when instantiating objects. For example, with the ''ClickerCounter'' class we've been developing so far: However, there will be times when you want to override these default values when instantiating objects. For example, with the ''ClickerCounter'' class we've been developing so far:
  
-<file java> +<file java ClickerCounter.java> 
 public class ClickerCounter { public class ClickerCounter {
  
Line 42: Line 42:
 </file> </file>
  
-upon instantiation, the ''maxCount'' member variable will be initialized to zero. Given that a counter that counts from zero to zero isn't very useful, it would be good if this were automatically initialized on object instantiation to some other values.+upon instantiation, the ''maxCount'' member variable will be initialized to zero. Given that a counter that counts from zero to zero isn't very useful, it would be good if this were automatically initialized to some other valueOne way to do this is to set initial values in the member variable definition:
  
-To do this, we can use a **constructor**: a member method that runs automatically whenever you instantiate the object.+<code java>  
 +public class ClickerCounter {
  
-A constructor that does this initialization as well as initializing ''count'' looks like:+    // Member variables 
 +    private int count = 0; 
 +    private int maxCount = 9999; 
 + 
 +    ... 
 +
 +</code> 
 + 
 +With the above modification, when a ''ClickerCounter'' is instantiated, its ''maxCount'' will be set to 9999. We also explicitly initialized ''count'' to zero in the constructor so that someone reading the code would be sure that the member variable gets the initialized with the value we wanted rather than wondering whether we forgot about initializing it. 
 + 
 +This approach works fine if your class is fairly simple. 
 + 
 +===== Default constructors ===== 
 + 
 +Another way to initialize a class is by using a **constructor**: a method that runs automatically whenever you instantiate the object. Constructors are better suited to more complex situations, and they are not limited to just initializing member variables. They can do anything you can normally do in a method. For example, you might want to output that your object was successfully created. 
 + 
 +A constructor that does does this looks like:
  
 <code java> <code java>
Line 55: Line 72:
     // Default constructor     // Default constructor
     public ClickerCounter() {     public ClickerCounter() {
 +        // initialize member variables
         maxCount = 9999;         maxCount = 9999;
         count = 0;         count = 0;
 +        
 +        // output success
 +        System.out.print("Successfully created a ClickerCounter ");
 +        System.out.print("with a maxCount of " + maxCount + '.');
     }     }
          
Line 63: Line 85:
 </code> </code>
  
-Note the syntaxA constructor does not have a return type, is declared with ''public'' access, and has the same name as the class. Now when we instantiate a ''ClickerCounter'':+Note the syntaxA constructor
 +  * does not have a return type (not even ''void''). 
 +  * has the same name as the class. 
 +  * is declared with ''public'' access. 
 + 
 +Now when we instantiate a ''ClickerCounter'':
  
 <code java> <code java>
Line 69: Line 96:
 </code> </code>
  
-''myClicker'''s ''maxCount'' will be set to 9999. We also initialized ''count'' to zero in the constructor so that someone reading the code would be sure that the member variable got the initialized with the value we wanted rather than wondering whether we forgot about it.+''myClicker'''s ''maxCount'' will be set to 9999''count'' will be set to zero, and a message indicating successful instantiation will be printed.
  
-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.+In short, constructors are used to initialize objects and can do so in ways that go beyond simple member variable initialization.
  
 ===== Parameterized constructors ===== ===== Parameterized constructors =====
Line 84: Line 111:
     // Parameterized constructor     // Parameterized constructor
     public ClickerCounter(int maxCount) {     public ClickerCounter(int maxCount) {
 +        // initialize member variables
         this.maxCount = maxCount;         this.maxCount = maxCount;
         count = 0;         count = 0;
 +        
 +        // output success
 +        System.out.print("Successfully created a ClickerCounter ");
 +        System.out.print("with a maxCount of " + maxCount + '.');
     }     }
          
Line 93: Line 125:
  
 You can define as many constructors as you want. You are not required to define a constructor, but if you define constructors, you must always define a default constructor. You can define as many constructors as you want. You are not required to define a constructor, but if you define constructors, you must always define a default constructor.
 +
 ===== toString() ===== ===== toString() =====
  
java/initializing_classes_and_constructors.txt · Last modified: 2020/09/16 18:15 by mithat

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki