Title: Classes and Objects
1Classes and Objects
- A class is a collection of data and methods that
operate on that data. - A class models some real world object.
- Example Circle - how would you define it?
2Circle class
class Circle double x,y //coordinates of
center double r //radius public double
circumference()return 23.14159r public
double area()return 3.14159rr
3Objects are instances of a class
Circle c c new Circle() c.x2.0 c.y2.0
c.r1.0 double a a c.area()
4Constructor
public Circle(double x, double y, double
r) this.xx this.yy this.rr Circle c
new Circle(1.414, -1.0, .25)
5Multiple Constructors
Public Circle(double r)x0.0 y0.0
this.rr //special use of this to call
constructor public Circle(double
r)this(0.0,0.0,r)
6Class variable
- Use static keyword
- static int num_circles 0
- num_circles //in the constructor
7Accessing class variables
- System.out.println(Number of circles created
Circle.num_circles)
8 class methods
- Declared with the static keyword
- it is not passed a this reference
- it is invoked using the class name instead of an
object
9Class method example
Public boolean isInside(double a, double
b) double dx a-x double dy b-y double
dist Math.sqrt(dxdx dydy) if(dist lt r)
return true return false