Specifying initial values in a class definition : Defining Class « Class Definition « Java Tutorial






class A {
  A(int marker) {
    System.out.println("Bowl(" + marker + ")");
  }

  void f(int marker) {
    System.out.println("f(" + marker + ")");
  }
}

class B {
  static A a = new A(1);

  B() {
    System.out.println("Table()");
    staticA.f(1);
  }

  void f2(int marker) {
    System.out.println("f2(" + marker + ")");
  }

  static A staticA = new A(2);
}

class C {
  A a = new A(3);

  static A staticA = new A(4);

  C() {
    System.out.println("Cupboard()");
    staticA.f(2);
  }

  void f3(int marker) {
    System.out.println("f3(" + marker + ")");
  }

  static A staticA2 = new A(5);
}

public class MainClass {
  public static void main(String[] args) {
    System.out.println("Creating new Cupboard() in main");
    new C();
    System.out.println("Creating new Cupboard() in main");
    new C();
    t2.f2(1);
    t3.f3(1);
  }

  static B t2 = new B();

  static C t3 = new C();
}
Bowl(1)
Bowl(2)
Table()
f(1)
Bowl(4)
Bowl(5)
Bowl(3)
Cupboard()
f(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f(2)
f2(1)
f3(1)








5.1.Defining Class
5.1.1.What Is a Java Class?
5.1.2.Fields
5.1.3.Defining Classes: A class has fields and methods
5.1.4.Creating Objects of a Class
5.1.5.Checking whether the object referenced was of type String
5.1.6.Class declaration with one method
5.1.7.Class declaration with a method that has a parameter
5.1.8.Class that contains a String instance variable and methods to set and get its value
5.1.9.Class with a constructor to initialize instance variables
5.1.10.Specifying initial values in a class definition