Declaring Java Classes Declaring Attributes Declaring Methods Declaring a Constructor

J.E.D.I.

1.3 Java Program Structure

This section summarizes the basic syntax used in creating Java applications.

1.3.1 Declaring Java Classes

classDeclaration ::= modifier class name { attributeDeclaration constructorDeclaration methodDeclaration } where modifier is an access modifier, which may be combined with other types of modifier. Coding Guidelines: means that there may be 0 or more occurrences of the line where it was applied to. description indicates that you have to substitute an actual value for this part instead of typing it as ease. Remember that for a top-level class, the only valid access modifiers are public and package i.e., if no access modifier prefixes the class keyword. The following example declares a SuperHero blueprint. class SuperHero { String superPowers[]; void setSuperPowersString superPowers[] { this.superPowers = superPowers; } void printSuperPowers { for int i = 0; i superPowers.length; i++ { System.out.printlnsuperPowers[i]; } } }

1.3.2 Declaring Attributes

attributeDeclaration ::= modifier type name [= default_value]; type ::= byte | short | int | long | char | float | double | boolean | class Coding Guidelines: [] indicates that this part is optional. Here is an example. public class AttributeDemo { private String studNum; public boolean graduating = false; protected float unitsTaken = 0.0f; Introduction to Programming II Page 12 J.E.D.I. String college; }

1.3.3 Declaring Methods

methodDeclaration ::= modifier returnType nameparameter { statement } parameter ::= parameter_type parameter_name[,] For example: class MethodDemo { int data; int getData { return data; } void setDataint data { this.data = data; } void setMaxDataint data1, int data2 { data = data1data2? data1 : data2; } }

1.3.4 Declaring a Constructor

constructorDeclaration ::= modifier className parameter { statement } If no constructor is explicitly provided, a default constructor is automatically created for you. The default constructor takes no arguments and its body contains no statements. Coding Guidelines: The name of the constructor should be the same as the class name. The only valid modifier for constructors are public, protected, and private. Constructors do not have return values. Consider the following example. class ConstructorDemo { private int data; public ConstructorDemo { data = 100; } ConstructorDemoint data { this.data = data; } } Introduction to Programming II Page 13 J.E.D.I.

1.3.5 Instantiating a Class