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

Next revision
Previous revision
java:constructor_basics [2020/09/12 02:04] – created mithatjava:initializing_classes_and_constructors [2020/09/16 18:15] (current) – [equals(other)] mithat
Line 1: Line 1:
-======  Java Constructor Basics ====== +======  Initializing Classes and Constructors ======  
 + 
 +===== Initializing member variables ===== 
 + 
 +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: 
 + 
 +<file java ClickerCounter.java>  
 +public class ClickerCounter { 
 + 
 +    // Member variables 
 +    private int count; 
 +    private int maxCount; 
 + 
 +    // Accessors and mutators 
 +    public int getCount() { 
 +        return count; 
 +    } 
 + 
 +    public void setMaxCount(int maxCount) { 
 +        if (maxCount > 0) { 
 +            this.maxCount = maxCount; 
 +        } else { 
 +            System.out.println("Invalid maximum count: " + maxCount); 
 +        } 
 +    } 
 + 
 +    // Interface methods 
 +    public void click() { 
 +        if (count < maxCount) { 
 +            count++; 
 +        } else { 
 +            count = 0; 
 +        } 
 +    } 
 + 
 +    public void reset() { 
 +        count = 0; 
 +    } 
 +
 +</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 to some other value. 
 + 
 +One way to do this is to set initial values in the variable declarations: 
 + 
 +<code java>  
 +public class ClickerCounter { 
 + 
 +    // 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 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 ===== ===== 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:+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. You can do anything in a constructor that you can do in a regular method.
  
-...+For example, after initializing the state of your object, you might want to output that your object was successfully createdA constructor that does does this 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.+<code java> 
 +public class ClickerCounter {
  
-Soin 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.+    ... 
 +     
 +    // Default constructor 
 +    public ClickerCounter() { 
 +        // initialize member variables 
 +        maxCount = 9999; 
 +        count = 0; 
 +         
 +        // output success 
 +        System.out.print("Successfully created a ClickerCounter "); 
 +        System.out.print("with a maxCount of " + maxCount + '.'); 
 +    } 
 +     
 +    ... 
 +
 +</code> 
 + 
 +Note the syntax. A 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> 
 +var myClicker = new ClickerCounter(); 
 +</code> 
 + 
 +''myClicker'''s ''maxCount'' will be set to 9999''count'' will be set to zero, and a message indicating successful instantiation will be printed. 
 + 
 +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 =====
 +
 +The above is a **default constructor** because it has no parameters. It's also possible to define constructors that have parameters. Such a constructor is called a **parameterized constructor**:
 +
 +<code java>
 +public class ClickerCounter {
 +
 +    ...
 +    
 +    // Parameterized constructor
 +    public ClickerCounter(int maxCount) {
 +        // initialize member variables
 +        this.maxCount = maxCount;
 +        count = 0;
 +        
 +        // output success
 +        System.out.print("Successfully created a ClickerCounter ");
 +        System.out.print("with a maxCount of " + maxCount + '.');
 +    }
 +    
 +    ...
 +}
 +</code>
 +
 +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() =====
Line 30: Line 144:
 </code> </code>
  
-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.+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 doing this now. 
 + 
 + 
 +===== equals(other) ===== 
 + 
 +Another method that you can define and is a good habit to get into defining is ''equals''. A very basic definition of `equals` is created automatically, but in almost all cases, you will want to change this functionality. An example of an ''equals'' method for the ''ClickerCounter'' class might look like: 
 + 
 +<code java> 
 +public boolean equals(ClickerCounter other) { 
 +    return (this.count == other.count &&  
 +            this.maxCount == other.maxCount); 
 +
 +</code> 
 + 
 +It's up to you to decide what "equals" means. In many cases, "equals" means that two objects of the same class have the same state. So, in the above definition, for two counter to be equal, both the count and the maxCount must be the same. Now to use this method, assuming both of the variables below refer to valid ''ClickerCounters'': 
 + 
 +<code java> 
 +if (myCounter.equals(yourCounter) { 
 +    System.out.println("Our counters are the same."); 
 +} else { 
 +    System.out.println("Your counter and mine are not the same."); 
 +
 +</code>
  
 Copyright © 2020 Mithat Konar. All rights reserved. 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