Advertisement
MrDoyle

19) Static (and Final)

Feb 10th, 2021
766
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.83 KB | None | 0 0
  1. class Thing{
  2.  
  3.     //cannot change the value of "final" once has been initialized
  4.     public final static int LUCKY_NUMBER = 7;
  5.  
  6.     public String name;
  7.     public static String description;
  8.  
  9.     //because count is static, there is only one copy of count that exists in the class
  10.     public static int count = 0;
  11.  
  12.     public int id;
  13.  
  14.     public Thing(){
  15.         id = count;
  16.         count ++;
  17.     }
  18.  
  19.     public void showName(){
  20.         System.out.println("Object id: " + id + ", " + description + ": " + name);
  21.         Thing.showInfo();
  22.     }
  23.  
  24.     //can only be accessed within the class, but cannot be accessed by the declared objects in the main class
  25.     public static void showInfo(){
  26.         System.out.println(description);
  27.     }
  28.  
  29. }
  30.  
  31.  
  32. public class Main {
  33.  
  34.     public static void main(String[] args) {
  35.  
  36.         //because String description is static in the class, it is associated with the class, not the objects that are instantiated
  37.         //this works because the variable in the Thing class has been set to "public", if set to "private" this will not work
  38.         Thing.description = "I am a thing";
  39.  
  40.         Thing.showInfo();
  41.  
  42.         System.out.println("Before creating objects, count is: " + Thing.count);
  43.  
  44.         Thing thing1 = new Thing();
  45.         Thing thing2 = new Thing();
  46.  
  47.         System.out.println("After creating objects, count is: " + Thing.count);
  48.  
  49.         //each object gets its own name
  50.         thing1.name = "Bob";
  51.         thing2.name = "Sue";
  52.  
  53.  
  54.         System.out.println(thing1.name);
  55.         System.out.println(thing2.name);
  56.  
  57.         //Accessing the static value of PI in the Math class
  58.         System.out.println(Math.PI);
  59.  
  60.         //Cannot change the constant value of PI
  61.         //Math.PI = 15;
  62.  
  63.         System.out.println(Thing.LUCKY_NUMBER);
  64.  
  65.         thing1.showName();
  66.  
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement