Box.java
1 2 3 4 5 6 7 8 9 |
public class Box { private String color; private int sides; public Box(String c, int s){ color = c; sides = s; } } |
Student.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public class Student { private int studentId; private String name; static String college = "Oswego"; public Student(int studentId, String name){ this.studentId = studentId; this.name = name; } public static String getCollege(){ return college; } public static void setCollege(String c){ college = c; } } |
StaticTest.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class StaticTest { public static void main(String[] args){ Student s1 = new Student(800, "Jim"); Student s2 = new Student(801, "James"); // Always access statics through the class, not the // instance objects! System.out.println(Student.getCollege()); // Accessing through the instances can lead to dangerous // misunderstandings of the code! e.g.: System.out.println(s1.getCollege()); Student.setCollege("Buffalo"); System.out.println(s1.getCollege()); } } |