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 class C {...} C o; // o is a reference o = new C(); // o is a reference to the created object
2
View Classes as Abstract Data Types (ADT) 4 ADT = (V,O) –V: a set of values –O: a set of operators 4 Information hiding, encapsulation, modularity
3
Hello.java class Hello { public static void main(String[] args){ Human joe = new Human(); joe.say(“Hello World!”); } class Human { public void say(String message){ System.out.println(message); }
4
An Integer Class (Int) value ::- 2 31.. 2 31 -1 add(Int) sub(Int) mul(Int) div(Int) print() get() put(int) class Int { private int value; public Int(int x){ // constructor value = x; } public Int add(Int x){ return new Int(value+x.value); } public Int sub(Int x){ return new Int(value - x.value); } public Int abs(Int x){ return new Int(x.value>=0 ? x.value : -x.value); } public void print(){ System.out.prinlnt(value); }
5
Using the Class Int class TestInt { public static void main(String[] args){ Int i = new Int(10); Int i1 = i.add(new Int(1)); Int i2 = i.sub(new Int(2)); Int i3 = i.mul(new Int(3)); Int i4 = i.div(new Int(4)); i.print(); i1.print(); i2.print();i3.print();i4.print(); }
6
A Rectangle Class int x,y,width,height; move(int,int) resize(float) print() class Rectangle { int x,y,width,height; public Rectangle(int x, int y, int width, int height){ this.x = x; this.y = y; this.width = width; this.height = height; } public void move(int x, int y){ this.x = x; this.y = y; } public void resize(float ratio){ width = (int)(ratio*width) ; height = (int)(ratio*height); }... }
7
Using the Class Rectangle class TestRectangle { public static void main(String[] args){ Rectangle r = new Rectangle(0,0,100,50); r.resize(2); r.move(100,100); r.print(); }
8
A Stack Class class Stack { private int top; private int val[]; public Stack(int size) { val = new int [size]; top = -1; } public boolean isEmpty() {return top == -1;} public boolean isFull() {return top == val.length-1;} public void push(int x) { if (!isFull()){ val[++top] = x; } else throw new RuntimeException("Stack overflow"); }... } int top; int val[]; isEmpty() isFull() push(int x) int pop() print()
9
Exercises Add the following methods to the class Rectangle. –int area() return the area of the rectangle –boolean isSquare() test whether the rectangle is a square 4 Define the class Queue by modifying the class Stack.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.