110 likes | 196 Views
CPSC 233 Tutorial. Xin Jan 31, 2011. Outlines. Non-OO OO (an exercise) Info hiding Overloading. non-OO OO. Identify classes Create classes Move code into class methods Call class methods from the main method. Exercise. OO Program (your task) Class Diagram is shown below.
E N D
CPSC 233 Tutorial Xin Jan 31, 2011
Outlines • Non-OO OO (an exercise) • Info hiding • Overloading
non-OO OO • Identify classes • Create classes • Move code into class methods • Call class methods from the main method
Exercise • OO Program (your task) • Class Diagram is shown below
Info Hiding • A class is a black box • It has some functions • Only make visible the interface • Hide from the user • How those functions are implemented is hidden from the user • internally used attributes • General rule (not strictly enforced) • Attributes be private • Some methods be public • Some methods be private • Why? • Implementations can be changed without notifying users • Neat interface • Safe • put everything in control • avoid invalid status
Car example • Source code available on my website
Overloading • Methods with the same name • different argument types (✓) • different # of arguments (✓) • Same arguments but different returned types (✗) • Overloaded methods are viewed as different methods • Differentiated by the compiler according to the arguments (signature) • Why overload? • logically clear • use the same name for the same method
Overloading constructor Class Foo{ private int num; private char ch; public Foo () {num = 0; ch = ‘ ‘;} public Foo (intnewNum) {num = newNum; ch = ‘ ‘;} }
Overloading operators • Operators are methods • 5/2 = 2 (arguments: int and int) • 5.f / 2.f = 2.5f (arguments: float and float) • 5.0 / 2.0 = 5.0 (arguments: double and double)
Overloading common methods Class Triangle { area (float base, float height) { // the basic method return (base * height / 2.f); } area (float A_x, float A_y, float B_x, float B_y, float C_x, float C_y){ // Heron’s formula a = edgeLenAB(); b = edgeLenAB(); c = edgeLenAB(); float s = (a + b + c) / 2.f; return Math.sqrt(s * (s-a) * (s-b) * (s-c)); } area (float a, float b, float angle_a_b){ // trigonometry return a * b * Math.sin(angle_a_b) / 2.f; } }
Exercise • Procedural program (available on tutorial website) import java.util.Scanner; public class CircleCalculator{ public static void main (String [] args) { double area; double radius; double circumference; final double PI = 3.14; Scanner in = new Scanner(System.in); System.out.print("Enter the radius for the circle: "); radius = in.nextDouble (); area = PI * radius * radius; circumference = 2 * PI * radius; System.out.println("The area of the circle is: " + area); System.out.println("The circumference of the circle is: " + circumference); } }