java class structure. class structure package declaration import statements class declaration class...

17
Java Class Structure

Upload: myrtle-morrison

Post on 18-Jan-2016

217 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable

Java Class Structure

Page 2: Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable

Class Structure• package declaration

• import statements

• class declaration

• class (static) variable declarations*

• instance variable declarations*

• constructor*

• class (static) methods*

• instance methods*

• * order immaterial

Page 3: Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable

Package Declaration• package packageName;• first statement in the .java file (excepting comments)• package components separated by dot; e.g.,

package uwt.css142.examples;• packaged class files must live in a parallel directory

structure; e.g.,

C:\java\classes\uwt\css142\examples• CLASSPATH environment variable must point to parent

directory; e.g.,

set CLASSPATH=.;C:\java\classes

Page 4: Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable

Import Statements

• import packageName.className;

• import packageName.*;

• OR use fully-qualified name of class

• java.lang.* is imported automatically

• classes in the same package as the class being written don’t need to be imported

• import java.awt.Font;• import java.awt.*;• java.awt.Font f =

new java.awt.Font(...);

Page 5: Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable

Class Declaration• [VisibilityModifier] class ClassName [extends

SuperClassName] [implements SomeInterface[, AnotherInterface]] {

• visibility: public, default• a public class must live in a file of the same name, with

a .java suffix– this implies only one public class per file

• a class extends java.lang.Object by default• public class MyClass extends Applet implements ActionListener, ItemListener

Page 6: Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable

Visibility Modifiers

• public - visible everywhere

• protected - visible in subclasses and within the package

• default - visible within the package (no keyword)

• private - visible within the class only

Page 7: Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable

Variable Declarations• [visibility][static][final]type name [= value];• visibility: public, protected, private, default• kinds of variables

– class (static) variables– instance variables– local variables (visibility modifiers do not apply)

• final keyword indicates that the initial value of the variable cannot be changed– Can only be assigned to once– naming convention: all uppercase, with underscores– e.g,final double METERS_PER_FOOT = .3048;

Page 8: Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable

Class (static) Variables• not associated with an instance of the class (i.e, an object)• are declared within a class but not inside any method• are declared with the static keyword• only one copy exists, no matter how many objects• accessible to all objects

private static int count;private static int nextAcctNo;

• public class (static) constants:public static final int BOLD = 1;public static final int ITALIC = 2;public static final int PLAIN = 4;– accessed through the class name: Font.BOLD

Page 9: Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable

Instance Variables• Hold the instance data for objects

• are declared within a class but not inside any method

• do not have the static keyword

• each object has its own copy

• are available throughout the class

• are usually hidden private String text; // hidden data

public void setText (String s) // setter

public String getText() // getter

Page 10: Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable

Local Variables• are defined inside the body of a method, loop, or

other statement block ({}), or in a parameter list, or in for statement

• have no visibility modifier

• known only within the code block where defined

• can shadow instance variables of same namepublic class BankAccount {

private double balance; // instance variable

public BankAccount (double initBalance) {

double balance = initBalance; // error

}

...

Page 11: Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable

Method Definition• [visibility] [static] returnType methodName ([Type param1], [Type param2], ...)• the body of the method is delineated by { }• parameters are only known within the method (local variables)• a return type must be declared; if the method returns nothing, use void• if not returning void, every path through the method must have a

return statement which returns data of the specified type• There is an implied return statement at the end of a method that

returns void; return statements may be inserted at other points • e.g.,

public static int computeSum (int a, int b) { return a + b;}

• to invoke the above method from within the same class:int sum = computeSum (2*count, 145);int ans = computeSum (computeSum(4,9), 145);

Page 12: Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable

Instance Methods • the default; no static keyword

• must be invoked on an instance of the class, i.e., an object

• purpose is to access instance data

• e.g.,

public class BankAccount {

private double balance;

public double deposit (double amount) {

balance = balance + amount;

return balance;

}

}• invoked via an object of that class:

BankAccount myAcct = new BankAccount (1000);

double bal = myAcct.deposit (500);

Page 13: Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable

Class (static) Methods • identified by the static keyword

• NOT associated with an object

• e.g.,

public class Utilities {

public static double centToFahr(double cent)

{

return cent * 9 / 5. + 32;

}

}• invoked via the class name:

double f = Utilities.centToFahr (20.)• all data must be hard-coded or passed as parameter (or static)

• cannot access instance data

Page 14: Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable

Method Overloading• Suppose you want methods to operate on different parameter types:

– void printInt (int i)– void printDouble (double d)– void printString (String s)

• Another way: methods of the same name are distinguished by their parameter types– void print (int i)– void print (double d)– void print (String s)

• Same name, but no compiler error as long as parameters are different in number and/or type; (return type not part of signature)

• Often used in the java API; e.g, valueOf(), indexOf() in String class have several variations

Page 15: Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable

Constructors• Invoked by the new operator

to create an object• Definition similar to method

syntax, except no static option and no return type

• Constructor name is same as that of class

• Constructors may take parameters

• May be more than one constructor with different parameters (overloaded)

• Should generally be public• Supply only if needed to

initialize instance data

public class Student {public Student ()

{...}

public Student(String name)

{...}

public Student(String name,

String major)

{...}

public Student(String name,

String major,

double gpa,

int credits)

{...}

}

Page 16: Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable

Constructors (continued)• With overloaded constructors, it is common to have one

constructor do all the work; the other constructors simply call it with the required parameters

• this (…); when used in a constructor, invokes another constructor of the same class

public class Student {public Student(String name, String major){

this (name, major, 0.0, 0)

}

public Student(String name, String major,

double gpa, int credits){

this.name = name;

...

}

}

Page 17: Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable

Constructors (cont.)• Every class must have a constructor

• The first thing a constructor must do is invoke its superclass constructor super(); or another constructor of the same class this();

• If the author does not supply a constructor, the compiler will create one that takes no arguments and just calls its superclass constructor

• If the author supplies any constructor, the compiler does not create the no-args constructor

• If the author’s constructor does not invoke the superclass constructor, the compiler inserts an invocation of the no-args superclass constructor; if the superclass doesn’t have such a constructor, the class won’t compile

• In this way, the compiler assures the chaining of constructor invocations, from superclass to subclass

• supply a constructor if there is data to pass, or if the superclass doesn’t have a no-args constructor