[go: up one dir, main page]

0% found this document useful (0 votes)
49 views61 pages

Fundamentals of Object-Oriented Robot Programming in Java: Newport Robotics Group

The document provides an overview of object-oriented programming concepts like classes, objects, methods, and constructors. It uses examples like a robot class to illustrate key ideas. A class defines the data and behaviors of an object, and includes fields to store data, methods to perform actions, and constructors to initialize new objects. Methods can be accessors to retrieve data or mutators to modify it. The document also discusses static elements that are the same across all class instances versus non-static elements that can vary.

Uploaded by

Knayamp
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views61 pages

Fundamentals of Object-Oriented Robot Programming in Java: Newport Robotics Group

The document provides an overview of object-oriented programming concepts like classes, objects, methods, and constructors. It uses examples like a robot class to illustrate key ideas. A class defines the data and behaviors of an object, and includes fields to store data, methods to perform actions, and constructors to initialize new objects. Methods can be accessors to retrieve data or mutators to modify it. The document also discusses static elements that are the same across all class instances versus non-static elements that can vary.

Uploaded by

Knayamp
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 61

Newport Robotics Group

Fundamentals of ObjectOriented Robot Programming


in Java
Day 3 10/4/2012

T/Th, 6:30 8:30 PM


Big Picture School

You will teach me what a method is!

Review of Methods

What is a method?
A

method is a block of code that


performs some operation
Think of it as a machine that both
inputs and outputs data
An

accessor (getter) method


provides access to data
A mutator (setter) method changes
data
3

Methods
Think

of a method from our earlier


example: We need to find the
average of two integers.
What are the inputs of the method?
What is the output of the method?
What does the method do?
What is the method called?

Method Name
A

method name must describe what


the method does accurately and
succinctly
Use camelCase starting with a
lowercase letter
Example:

sumOfThreeInts

Parameters
Inputs

to a method are called


parameters or arguments
Just as before, we need to tell the
compiler what data types the
parameters are by declaring them
Separate parameters by commas
Example:

int a, int b
6

Return Type
When

a method outputs a value, we


say that it returns that value
We must specify to the compiler
what data type the method outputs
This is called the return type
If

a method has no output, its return


type is called void
7

Access Modifiers
A

method should specify an access modifier


to control who can use the method
The most common access modifiers are
public and private
Public methods can be used by anyone
Private methods can only be used internally
Example: In an ATM machine, the method
enterPIN should be public (users can press
buttons), but the method releaseMoney
should be private and only used internally
8

Method Signature
The

method signature is the first line


of any method and tells the compiler
what the method does
The method body, or code that runs
when the method is used, must
follow the contract set up by the
method signature
Example: if the signature says that
the method outputs an int, the body
cannot output a boolean.
9

Method Signature
We

can make a method signature by


putting the following parts together:
Access Modifier
Return Type
Method Name
Parameters (in parentheses)

If there are no parameters, use empty parentheses (). Do not


put void.

Example:
public int sumOfThreeInts(int a, int b, int c)
Access Modifier Return Type

Method Name

Parameters
10

Method Body
The

body of the method is a block of code


between two curly braces
The method body uses the inputs and
generates the output
The return statement indicates the output
public int sumOfThreeInts(int a, int b, int c)
{
Method
// ...(Method body goes here)
Signature
return something; //something is an int
}
11

Implementation
When

we write the code for a method,


we say that we implement that
method

public int sumOfThreeInts(int a, int b, int c)


{
Implementation
int sum = a + b + c;
return sum;
}
12

Calling Methods
Now

we have created our method, or


machine. However, just because it
knows what to do doesnt mean it
gets used
Example: A washing machine may have

all the code it needs to run, but nothing


will happen until the user puts clothes in
and turns it on
To

make a method run, we call it.

13

How to Call a Method


To

call a method, put the method name


and values for any parameters in
parentheses
Example: sumOfThreeInts(5, 2, 1)
In this case, the method will run with a having a
value of 5, b with a value of 2, and c with a value
of 1.

However, we dont do anything with the


value the method returns in this case
14

Using a Method Call


We

can make use of method calls by


storing their return values in a
variable.

Example:

int x = sumOfThreeInts(1, 4, -3);

In this example, after the line of code


runs, x will have a value of 2.
15

Day 2 Review exercise


Write

a method that averages four


integers and a double
You must be able to print out your
answer
Remember how doubles operate

16

Possible Solution
public double average(int a, int b, int c,
double d){
double a = a+b+c+d;
a = a/2;
return a;
}
public static void main(String[] args){
System.out.println(average(6,9,17,9.5)+);
//prints out 10.375
}

17

Day 2 Review Exercise


Write

a method to
convert radians to degrees
convert degrees to radians
Remember:

360 = 2 radians

18

Conditionals and Loops

19

Conditionals
if
else
else

if

Allow

us to create logic in our


programs do things based on
whether statements are true or false

20

Using Conditionals
boolean adult = false;
boolean under16 = false;
if (age < 16)
{
adult = false;
under16 = true;
}

else if (age < 18)


{
adult = false;
under16 = false;
}
else
{
adult = true;
under16 = false;
}
21

Loops
While

loops
Do-while loops
For loops
For-each loops (will be covered later)

22

While Loops
Runs

while condition is true

while (condition)
{
// Do this!
}

23

Do-While Loops
Runs

while condition is true, at least


once!

do
{
// Do this!
} while (condition);

24

For Loops
Combines

declaration, initialization, condition, and

update
for (declaration/initialization; condition; update)
{
// Do this!
}
Example:
for (int i = 1; i < 10; i++)
{
// Do thishow many times?
}
25

Any Questions?
Before we move on?

26

Do you think you can handle


this?
Fizzbuzz is a test some companies use
to weed out those with actual
programming skill
Do you want to try it?

27

Practice: FizzBuzz
Is

a game where you count up by


1, starting at 1.
Whenever the number is a multiple
of:
5, you say Fizz!
7, you say Buzz!
5 and 7, you say FizzBuzz!
Else, say the number

Make

a method fizzBuzz() that plays


the above game to 50.

DONT LOOK AT THE


ANSWER

29

FizzBuzz Solution
public static void main(String[] args){
for(int i = 1; i <= 50; i++){
if(i%5==0 && i%7==0){
System.out.println(FizzBuzz!);
}else if(i%5 == 0){
System.out.println(Fizz!);
}else if(i%7 == 0){
System.out.println(Buzz!);
}else{
System.out.println(i);
}
}
}

30

New Stuf
Time to move on!

31

Readabil
ity

Constants
You

cant change the value.


Use the key-word final.
Uses a different naming convention.
Helps readability.
Instead

of:

int num2 = num1 + 7;


final int NUM2MODIFIER = 7;

int num2 = num1 + NUM2MODIFIER;

Repetitive Code
To

improve readability, you can often


remove repetitive code, for example:
Instead of:
double quadratic1 = (-b + Math.sqrt(b*b
4*a*c))/(2*a);
double quadratic2 = (-b - Math.sqrt(b*b
4*a*c))/(2*a);
Use:
double root = Math.sqrt(b*b 4*a*c);
double quadratic1 = (-b + root)/(2*a);
double quadratic2 = (-b - root)/(2*a);

Practice: BetterFizzBuzz
Make

a method betterFizzBuzz() that


uses constants and gets rid of
repetitive code.

Overloading
A

method is overloaded if there are


two or more methods with the same
name, but different data types for
the parameters and/or number of
parameters
Allows a method to perform similar
tasks with different inputs
Example: The System.out.println
method is overloaded so it can print
different types of data: Strings, ints,

36

Overloading Methods
Say

we have two methods:

public static double mean(int a, int b) { }


public static double mean(int a, int b, int c)
{}
The

compiler will match up a method call to the


correct method implementation based on the
count and types of the given parameters
mean(2, 3) will call the first method
mean(5, 7, 1) will call the second method
mean(1) will result in an error, as there is no

matching method for mean(int)


mean(1.0) will also be an error: no method
mean(double)

37

Questions?

Reviewing Object
Oriented Programming
Ready? Lets go!

39

What is Object-Oriented
Programming?
Object

Oriented Programming (OOP) is


a methodology that breaks programs
into discrete, reusable units of code
called objects which attempt to model
things in the real world
An object usually contains both data
and a set of operations that can be
performed on that data
An object-oriented program is just a
collection of cooperating objects that
40

But what does a class


do?
A class defines 3 things about a type
of object:
Information the object contains
(data)
What the object does
How the object is made (Well touch
on this later)

41

Class Examples a Box


What

information it has?

Length, Width, Height


Type of Material
Whether it is open or closed

What

it does?

Volume
Surface Area
Open/Close
Collapse
42

Class Examples a
Robot
What

information it has?

weight
motors
position

What

it does?

Move
Speak
Develop intelligence (ex: Skynet)
43

The Robot Example


Since

a robot is a fairly easy concept


to visualize, we will be using it as
one of our examples.
We will continue to define our robot
class as we learn new concepts,
adding to it each time.
Any Questions so far?
44

Classes

Instance Fields
Stores

variables in objects
Looks like:
access static type name;
i.e. private double GPA;
Assigned values in constructor,
mutator methods
Accessed by accessor methods, or is
public.

Constructors
Used

to create new objects.


Looks like:
public ClassName(parameters)
{
varName1 = myVarName;
}

Called

by:

ClassName name = new ClassName(parameters);

Methods
Does

things:
Looks like:
access static returnTypename(parameters)
{
//code goes here
}

Called

by:

objectName.methodName(parameters);

Accessor vs. Mutator


Methods
Accessors

access values, returning


instance variables / other values.
Mutators mutate values, modifying
an instance variable in the object.

What is Static?
static

refers to whether the method


or variable belongs to the class, and
is the same, or static, throughout all
instances of the class.
For Example, the class Math has
static methods such as .abs()
(Absolute Value). In order to use this
you do not need to create a new
instance of Math, you just do
Math.abs();

Testers
Now

that we know how to use


classes, were going to test them,
without a main method directly
inside the class. We do this using a
tester.

Is

another class that is usually called


ClassNameTester.

Testers (cont.)
Testers

contain a main method, then


construct an object of the class it is
testing.
It then uses the methods to test and
see if it works.

Questions?

55

Practice: Robot
What

variables would our Robot


need to store?

What

methods would our Robot need


to do?

Practice: Robot (cont.)


Instance

Fields:
// how much the robot weighs in pounds
private double mass;
//true if the robot is on; false if the robot is
off
private
boolean isAwake;

Constructor:
public (double themass, boolean awake)
{
mass = themass;
isAwake = awake;
}

Your turn folks!


Come

up with two unique instance


fields for a robot
With these instance fields, make two
constructor methods
Creativity is encouraged!

58

Practice: Robot (cont.)


Methods:

public double getmass()


{
return mass;
}
public boolean isOn()
{
return isAwake;
}

Practice: Robot (cont.)


public void wakeUp()
{
isAwake = true;
System.out.println(beeeeeeeep...");
}

public void goToSleep()


{
isAwake = false;
System.out.println(offfffffff...");
}

Practice: Robot (cont.)


Tester:
public class RobotTester
{
public static void main(String[] args)
{
Robot chuwei = new Robot(445.0, false);
chuwei.wakeUp();
chuwei.(35.0);
double money = chuwei.getMoney(240);
System.out.println("chuwei stole " + money + "
dollars!");
chuwei.turnOff();
System.out.println("chuwei now weighs " +
chuwei.getmass() + " pounds.");
}
}

HW/Practice: Box
Do

a class box with instance


variables length, width, height,
isOpen, and material(String).
It should contain accessors/mutators
for all of the above, and the methods
getVolume, getSurfaceArea, and
toString, which returns a String
representation of the box.
Also, make a tester.

You might also like