Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Objects & Classes

Similar presentations


Presentation on theme: "Introduction to Objects & Classes"— Presentation transcript:

1 Introduction to Objects & Classes
Paul Bui

2 Introduction Group related information and methods (functions) together Design classes with attributes and behaviors in mind Circle Example Attributes? Behaviors?

3 Building a Class - Attributes
Name the java file the same name as the class (e.g. Circle.java) Capitalize the class name Put the attributes at the top of the class and make them private It’s nice to give them default values too (e.g. radius = 0.0) public class Circle { private double radius = 0.0; ... }

4 Building a Class - Constructors
Used when the object is instantiated String str = new String(); No return type Always has the same name as the class Can have 0 or more parameters Two types:“default constructor” and “specific constructors” Example: public Circle() // “default constructor” has 0 parameters { }

5 Building a Class - Constructors
“specific constructor” takes parameters that set the attributes Example: public Circle(double newRadius) { radius = newRadius; }

6 Building a Class - Methods
Methods are defined and declared using the following template: public RETURNTYPE METHODNAME(PARAMETERS) { //METHOD CODE } Example: public double getArea() return *radius*radius;

7 Naming Methods Naming Methods Parts of a method
Capitalize every word in the method name EXCEPT for the first Example: thisIsAGoodMethodName() No spaces in the method name Parts of a method All methods except for the constructors have the same form RETURNTYPE METHODNAME ( PARAMETERS )

8 Methods – Getters & Setters
Accessors (Getters) Used to access attributes 0 parameters Example public double getRadius() { return radius; }

9 Methods – Getters & Setters
Mutators (Setters) Used to change attributes Most of the time has a return type of void Example public void setRadius(double newRadius) { radius = newRadius; }

10 Access Levels Controls whether or not the attribute or method can be seen/used outside of the class public, private, protected Put in front of class name, attributes, and methods


Download ppt "Introduction to Objects & Classes"

Similar presentations


Ads by Google