Chapter 12
Coding Classes

   12.1 Fields
   12.2 Constructors
   12.3 Methods
   12.4 Internal References to Static Features
   12.5 Internal References to Instance Features
   12.6 Assignment #13: Coding Classes

12.1 Fields

class prg { 
  public static void main ( String[] args ){ 
     MyClass obj; 
     System.out.println( MyClass.i1 ); 
     System.out.println( MyClass.i2 ); 
     obj = new MyClass(); 
     System.out.println( obj.i3 ); 
     System.out.println( obj.i4 ); 
} } 
class MyClass { 
  static int i1, i2 = 2; 
  int i3, i4 = 4; 
} 

12.2 Constructors

12.3 Methods

12.4 Internal References to Static Features

12.5 Internal References to Instance Features

Exercises

12.6 Assignment #13: Coding Classes

Due: Fr, May 9, midnight

Add to class ‘MyClass’ the needed features so that the given program will compile (under javac) into an executable code.

class lab13{ 
   public static void main(String[] args){ 
      MyClass var; 
      int i; 
      var = new MyClass(5.1); 
      MyClass.a = 5; 
      var.b = 2; 
      MyClass.c(); 
      var.d(); 
      i = var.e(); 
      var = MyClass.f(5); 
} } 
class MyClass{ 
 
} 
summary information
variables (fields, parameters, local variables) <modifiers> <type> <name>;
  • The modifiers are optional
  • The type can’t be void
  • Class fields must carry the static modifier
methods <modifiers> <return type> <name> ( <parameters> ) { <body> }
  • The modifiers are optional
  • Class methods must carry the static modifier
  • Methods with return types other than void should be called from an assignment instruction:
    <variable> = <call to method>
  • If the return type is not void, the body must include an instruction
    return <value>;
    providing a value of a type compatible with the one declared as a return type.
constructors <modifiers> <name> ( <parameters> ) { <body> }
  • A constructor must have a name identical to that of the owner class.
  • The modifiers are optional
Assume ‘lab13’ for the submit program. The program should be stored in a file named ‘lab13.java’.

Note: Files that fail to compile, and execute when applicable, will not be examined. They will be awarded a grade of 0 points.

Q&A