User Tools

Site Tools


java:defining_classes_in_java

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:defining_classes_in_java [2020/09/12 02:51] – [Our first Java class] mithatjava:defining_classes_in_java [2020/09/12 03:04] mithat
Line 1: Line 1:
-======  Defining Classes in Java ====== +======  Defining Classes in Java ======
  
 We are going to write a simple class for implementing a counter similar to one of these:((Picture from: "Totty Clicker - Gadgets at Play.com (UK)." Play.com (UK): DVDs, Music CDs, MP3s, Video Games, Books, Electronics & Gadgets - Free Delivery. [[http://www.play.com/Gadgets/Gadgets/4-/11566684/Totty-Clicker/Product.html?ptsl=1&ob=Price&fb=0#]] (accessed January 25, 2011).  We are going to write a simple class for implementing a counter similar to one of these:((Picture from: "Totty Clicker - Gadgets at Play.com (UK)." Play.com (UK): DVDs, Music CDs, MP3s, Video Games, Books, Electronics & Gadgets - Free Delivery. [[http://www.play.com/Gadgets/Gadgets/4-/11566684/Totty-Clicker/Product.html?ptsl=1&ob=Price&fb=0#]] (accessed January 25, 2011). 
Line 43: Line 43:
 </code> </code>
  
-This definition states that an instance of a ClickerCounter will consist of a ''count'' member variable, a method ''click()'' that increments the count, and a ''reset()'' method that resets the count.+This definition states that an instance of a ''ClickerCounter'' will consist of a ''count'' member variable, a method ''click()'' that increments the count, and a method ''reset()'' that resets the count.
  
-==== Where does the definition go? ====+==== Instantiation and use ====
  
 +The above is just a class definition. It doesn't actually make an object you can use. The code below shows you how to make, or **instantiate** a ''ClickerCounter'' and then call the object's methods to change the state of the object. 
  
-In Java, class definitions need to go in their own files, and the files need to be called the name of the class with the ''.java'' extension.((There are certain kinds of classes that don't need to be in their own file, but that's something we can't discuss yet.)) I have deliberately not used any comments in the definition so you can more easily see the code. 
  
-In the above, ''count'' is an attribute/instance variable that keeps track of the state of the object. the ''click'' and ''reset'' methods implement the behavior. In actuality, this is pretty crappy class definition for reasons we'll see later. But for now it's enough to get us started+<code java> 
 +var myCounter = new ClickerCounter();  // instantiate ClickerCounter
  
-==== Instantiation and use ====+myCounter.reset();  // count is 0 
 +myCounter.click();  // count is 1 
 +System.out.println(myCounter.count); 
 +myCounter.click();  // count is 2 
 +myCounter.click();  // count is 3 
 +System.out.println(myCounter.count); 
 +myCounter.reset();  // count is 0 
 +System.out.println(myCounter.count); 
 +</code>
  
-The above is just a class definition. It doesn't actually make an object we can use.+===== Where does the definition go? =====
  
-The program below shows you how to makeor **instantiate** a ''ClickerCounter'' and then call the object's methods to change the state of the object.+==== The easy-for-beginners way ==== 
 +If there's only one custom class in your program, an easy way to write your program is to incorporate the definition and the program'''main()'' method.
  
-<file java ClickerExample.java> +<file java ClickerCounter.java> 
-public class ClickerExample {+public class Counter { 
 + 
 +    // Class definition 
 +    int count; 
 +     
 +    void click(){ 
 +        count++; 
 +    } 
 +     
 +    void reset(){ 
 +        count = 0; 
 +    }   
  
 +    // Program's main method that uses the class
     public static void main(String[] args) {     public static void main(String[] args) {
         var myCounter = new ClickerCounter();  // instantiate a ClickerCounter         var myCounter = new ClickerCounter();  // instantiate a ClickerCounter
Line 76: Line 98:
 </file> </file>
  
 +This isn't generally recommended though because very often you will write more than one custom class in your program.
  
-===== Access specifiers ===== +==== The better way ==== 
-The ''ClickerCounter'' class definition above effectively encapsulates the state and behavior of clicker counter. But it has issuesFor example, if we change our example as follows:+ 
 +In Java, class definitions need to go in their own files, and the files need to be called the name of the class with the ''.java'' extension.((There are certain kinds of classes that don't need to be in their own file, but that's something we can't discuss yet.)) I have deliberately not used any comments in the definition so you can more easily see the code. 
 + 
 +In the above, ''count'' is an attribute/instance variable that keeps track of the state of the object. the ''click'' and ''reset'' methods implement the behavior. In actuality, this is pretty crappy class definition for reasons we'll see later. But for now it's enough to get us started 
 + 
 +==== Instantiation and use ==== 
 + 
 +The above is just a class definitionIt doesn't actually make an object we can use. 
 + 
 +The program below shows you how to make, or **instantiate** a ''ClickerCounter'' and then call the object's methods to change the state of the object.
  
 <file java ClickerExample.java> <file java ClickerExample.java>
Line 84: Line 116:
  
     public static void main(String[] args) {     public static void main(String[] args) {
-        var myCounter = new ClickerCounter();+        var myCounter = new ClickerCounter();  // instantiate a ClickerCounter
                  
-        myCounter.reset(); +        myCounter.reset();  // count is 0 
-        myCounter.count = 492341;  // <- LOOK HERE!+        myCounter.click();  // count is 1
         System.out.println(myCounter.count);         System.out.println(myCounter.count);
-        myCounter.click(); +        myCounter.click();  // count is 2 
-        myCounter.click();+        myCounter.click();  // count is 3 
 +        System.out.println(myCounter.count); 
 +        myCounter.reset();  // count is 0
         System.out.println(myCounter.count);         System.out.println(myCounter.count);
     }         }    
Line 96: Line 130:
 </file> </file>
  
-the object will happily oblige the user's wish to set the count to some arbitrary value. That's not something you can typically do with a clicker counter. In other words, the object offers no **protection** of its state. This is easy enough to solve with Java's access modifiers. Let's look at a modified version of our class definition that gives us some protection using access modifiers: 
- 
-<file java ClickerCounter.java> 
-public class ClickerCounter { 
-     
-    private int count; 
-     
-    public void click(){ 
-        count++; 
-    } 
-     
-    public void reset(){ 
-        count = 0; 
-    }     
-} 
-</file> 
- 
-Access modifiers are placed before the start of a member. Java offers four levels of protection, and they just so happen to all start with the letter 'p': 
-  * ''package'': this is what you get by default (i.e., when you don't specify anything, as in our first definition of the class). It means anything within the same package as the class definition is able to access the member. 
-  * ''public'': anyone anywhere can access the member. This is a good choice for methods that are part of the class' interface. 
-  * ''private'': only those of the same class can access the member.  
-  * ''protected'': only those of the same _or a derived_ class can access the member. ((The difference between ''private'' and ''protected'' won't be clear until you've studied class inheritance.)) 
- 
-With the changes made above, if we try to run ''ClickerExample'' we will see that the code will refuse to compile. When the compiler hits the statement 
- 
-<code java> 
-myCounter.count = 492341; 
-</code> 
- 
-it cannot access the ''count'' member of ''myCounter'' because we said it's private. Remember, we want our objects to be **self-governing**, and this helps make sure this is the case. 
- 
-<WRAP center round tip 80%> 
-In Java programming, it's considered a best practice to make all member variables ''private'' or ''protected'', except in some rare situations. 
- 
-Methods can be at whatever access level is appropriate for their use. If it is part of the class' interface, it should be ''public''. If it's for use only internally by the object, it will typically be ''private'' or ''protected''. 
-</WRAP> 
  
 Copyright © 2020 Mithat Konar. All rights reserved. Copyright © 2020 Mithat Konar. All rights reserved.
java/defining_classes_in_java.txt · Last modified: 2020/09/14 01:38 by mithat

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki