Download presentation
Presentation is loading. Please wait.
1
Review 4 View classes as modules Encapsulate operations Functions are static methods 4 View classes as struct types Encapsulate data 4 View classes as abstract data types Encapsulate both data and operations
2
Point p = new Point(0,0); Stack s = new Stack(); Life Cycle of Objects 4 Creating objects 4 Using objects 4 Cleaning up unused objects –An object becomes garbage when no variable refers to it p.x = 100; rx = s.pop();
3
Class Declaration in Java [public] [abstract] [final] class ClassName [extends ClassName] [implements Interfaces] { [VariableDeclaration | ConstructorDeclaration | MethodDeclaration | ClassDeclaration | InterfaceDeclaration]* }
4
Programming in Java4 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
5
Programming in Java5 Method Declarations MethodDeclaration ::= MethodHead MethodBody MethodHead ::= [AccessSpecifier ] [static] [final] ReturnType MethodName(T1 p1,..., Tn pn) MethodBody ::= { [LocalVariableDeclarationStatement | ClassOrInterfaceDeclaration | [Identifier :] Statement ]* } signature
6
Method Overloading 4 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; }
7
Programming in Java7 Constructor 4 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
8
Programming in Java8 Scope of Method Arguments class Circle { class Circle { int x, y, radius; int x, y, radius; public Circle(int x, int y, int radius) { public Circle(int x, int y, int radius) { this.x = x; this.x = x; this.y = y; this.y = y; this.radius = radius; this.radius = radius; }}
9
The Meaning of "static" 4 A static variable or method belongs to the class 4 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?
10
Programming in Java10 Static Variables (exercise) class AnIntegerNamedX { static int x; static int x; public int x() { public int x() { return x; return x; } public void setX(int newX) { public void setX(int newX) { x = 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());
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.