More Class Structure

Download Report

Transcript More Class Structure

Java Class Structure
Class Structure
•
•
•
•
•
•
•
•
•
package declaration
import statements
class declaration
class (static) variable declarations*
instance variable declarations*
constructor*
class (static) methods*
instance methods*
* order immaterial
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
Import Statements
• import java.awt.Font;
• import
packageName.className;
• import java.awt.*;
• import packageName.*;
• java.awt.Font f =
• OR use fully-qualified name
new java.awt.Font(...);
of class
• java.lang.* is imported
automatically
• classes in the same package as
the class being written don’t
need to be imported
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
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
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;
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
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
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 name
public class BankAccount {
private double balance; // instance variable
public BankAccount (double initBalance)
{
double balance = initBalance; // error
}
...
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);
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);
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
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
Constructors
• Invoked by the new operator public class Student {
public Student ()
to create an object
{...}
• Definition similar to method
public Student(String name)
syntax, except no static
option and no return type
{...}
public Student(String name,
• Constructor name is same as
that of class
String major)
{...}
• Constructors may take
parameters
public Student(String name,
String major,
• May be more than one
constructor with different
double gpa,
parameters (overloaded)
int credits)
• Should generally be public
{...}
}
• Supply only if needed to
initialize instance data
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
this (name, major,
}
public Student(String
double
this.name = name;
...
}
}
name, String major){
0.0, 0)
name, String major,
gpa, int credits){
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