100 likes | 247 Views
Review. 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. Life Cycle of Objects. Creating objects Using objects
E N D
Review • 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
Life 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();
Class Declaration in Java [public] [abstract] [final] class ClassName [extends ClassName] [implements Interfaces] { [VariableDeclaration | ConstructorDeclaration | MethodDeclaration | ClassDeclaration | InterfaceDeclaration]* }
Declaring Variables • 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 [AccessSpecifier] [static] [final] type VariableName Programming in Java
Method Declarations MethodDeclaration ::= MethodHeadMethodBody MethodHead ::= [AccessSpecifier ] [static] [final] ReturnType MethodName(T1 p1, ..., Tn pn) MethodBody ::= { [LocalVariableDeclarationStatement | ClassOrInterfaceDeclaration | [Identifier :] Statement ]* } signature Programming in Java
Method Overloading • A class can contain multiple methods that have the same name but different signatures class C { int m(int i){ return i+1; } double m(double f){ return f+2; } }
Constructor • 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 Programming in Java
Scope 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; } } Programming in Java
The 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 (x>y) ? x : y; • } • } What is wrong?
Static Variables (exercise) class AnIntegerNamedX { static int x; public int x() { return x; } public void setX(int newX) { x = newX; } } AnIntegerNamedX myX = new AnIntegerNamedX(); AnIntegerNamedX anotherX = new AnIntegerNamedX(); myX.setX(1); anotherX.x = 2; System.out.println("myX.x = " + myX.x()); System.out.println("anotherX.x = " + anotherX.x()); Programming in Java