CodeSnips

Wednesday, December 2, 2015

JGrasp - quick example 1

JGrasp is a tool similar to Linqpad to execute and explore code snippets. Here's a simple example of some Java code that shows the difference between static and instance class attributes. You should be able to past this code into JGrasp, save as Example1.java, and run/debug it.

public class Example1 {

  public static void main(String[] args) {
    
    System.out.println("Hello, World!!!\n");
        
    Square sq1 = new Square("My Square");
    Square sq2 = new Square("My Other Square"); 
        
    String line1 = 
      String.format("Squares have %d sides.\n", Square.Sides);

    String line2 = String.format("sq1 name is %s.", sq1.Name);
        
    System.out.println(line1+line2);
        
    System.out.println(String.format("sq2 name is \"%s\"",
        sq2.Name));
  }

}

class Square
{
  public static int Sides;
  public String Name;
    
  // Static initializer runs as part of class declaration.
  static {
    Sides = 4;
  }
    
  // Constructor - runs when instance is created by "new"
  public Square(String name)
  {
    Name = name;
  }
        
}


No comments:

Post a Comment