Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Thing{
- //cannot change the value of "final" once has been initialized
- public final static int LUCKY_NUMBER = 7;
- public String name;
- public static String description;
- //because count is static, there is only one copy of count that exists in the class
- public static int count = 0;
- public int id;
- public Thing(){
- id = count;
- count ++;
- }
- public void showName(){
- System.out.println("Object id: " + id + ", " + description + ": " + name);
- Thing.showInfo();
- }
- //can only be accessed within the class, but cannot be accessed by the declared objects in the main class
- public static void showInfo(){
- System.out.println(description);
- }
- }
- public class Main {
- public static void main(String[] args) {
- //because String description is static in the class, it is associated with the class, not the objects that are instantiated
- //this works because the variable in the Thing class has been set to "public", if set to "private" this will not work
- Thing.description = "I am a thing";
- Thing.showInfo();
- System.out.println("Before creating objects, count is: " + Thing.count);
- Thing thing1 = new Thing();
- Thing thing2 = new Thing();
- System.out.println("After creating objects, count is: " + Thing.count);
- //each object gets its own name
- thing1.name = "Bob";
- thing2.name = "Sue";
- System.out.println(thing1.name);
- System.out.println(thing2.name);
- //Accessing the static value of PI in the Math class
- System.out.println(Math.PI);
- //Cannot change the constant value of PI
- //Math.PI = 15;
- System.out.println(Thing.LUCKY_NUMBER);
- thing1.showName();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement