Title: Review
1Review
- View classes as modules
- Encapsulate operations
- Functions are static methods
- View classes as struct types
- Encapsulate data
- View classes as abstract data types
- Encapsulate both data and operations
2Life Cycle of Objects
- Creating objects
- Using objects
- Cleaning up unused objects
- An object becomes garbage when no variable refers
to it
Point p new Point(0,0) Stack s new Stack()
p.x 100 rx s.pop()
3Class Declaration in Java
public abstract final class ClassName
extends ClassName implements Interfaces
VariableDeclaration ConstructorDeclaratio
n MethodDeclaration
ClassDeclaration InterfaceDeclaration
4Declaring Variables
AccessSpecifier static final type
VariableName
- Access Specifier
- public accessible from anywhere
- private within the class
- (default) within the class and the package
- protected within the package and subclasses
- static class variable
- final constant
- Examples
5Method Declarations
MethodDeclaration MethodHead
MethodBody MethodHead AccessSpecifier
static final ReturnType MethodName(T1
p1, ..., Tn pn) MethodBody
LocalVariableDeclarationStatement
ClassOrInterfaceDeclaration Identifier
Statement
signature
6Method Overloading
- A class can contain multiple methods that have
the same name but different signatures
class C int m(int i) return i1
double m(double f) return f2
7Constructor
- Constructor
- Has the same name as the class
- A class can have any number of constructors
- Has no return value
- Uses "this" to call other constructors in the
class
8Scope of Method Arguments
class Circle int x, y, radius
public Circle(int x, int y, int radius)
this.x x this.y y
this.radius radius
9The Meaning of "static"
- A static variable or method belongs to the class
- A static variable is shared by all objects of the
class
class C public static void main(String
args) int a 10 int b
20 System.out.println(max(a,b))
int max(int x, int y) return
(xgty) ? x y
What is wrong?
10Static Variables (exercise)
class AnIntegerNamedX static int x
public int x() return x
public void setX(int newX) x newX
AnIntegerNamedX myX new AnIntegerNamedX() AnInt
egerNamedX anotherX new AnIntegerNamedX() myX.s
etX(1) anotherX.x 2 System.out.println("myX.x
" myX.x()) System.out.println("anotherX.x
" anotherX.x())