Object oriented
programming
Be
sure to read pages 82 -100
Summary of Fridays info
• We created a class Dog with:
– Two instance variables
– Four methods (two accessors and two mutators)
– This class was put into a file called Dog.java
• Then we created a class with a main(
) method so we could instantiate objects of type Dog
Looking at the Java syntax
• public class Dog
{ // instance
variables
private int age; // the age of the
dog
private String color; // the color of the
dog
// mutators change
the value of the instance variable
public void setColor(String col)
{
color = col; }
•
public
void setAge(int dogAge)
{
age = dogAge; }
//accessors return the value of an instance variable
public String getColor()
{
return color; }
•
public int
getAge()
{
return age; }
}
• public
class TestDogClass
{
public static void main(String args[
])
{
Dog zelda, yourDog, strayDog;
zelda = new Dog();
zelda.setAge(10);
zelda.setColor("brown");
yourDog = new Dog();
yourDog.setAge(32);
yourDog.setColor("red");
System.out.print("Zelda is
" + zelda.getColor())
System.out.println(" and
" + zelda.getAge ( ) + “ years old. “
• } // end main
} // end class
Using arguments to pass information
•
The mutator
method call in main has information about the dog’s color
•
This information
needs to be saved in the class object
•
This is done
using an argument in the mutator method
•
The method call
from main( )
zelda.setColor("brown");
• The method itself from the Dog class that saves the
information
public void setColor(String
col)
{
color = col; }
Adding to our Dog class
•
Add an instance
variable for the dog’s name
•
This means adding
a new accessor and mutator
•
Allow user input
to get the data
•
Use a constructor
to initialize the objects
Interactive input
• Import the Scanner class before the class declaration
in the file using input
• This would be the file with the main(
) method
import
java.util.Scanner;
• Declare an object of type Scanner
Scanner in = new Scanner(System.in);
• Use that object to call nextInt(
) or next( )
int
myNum= in.nextInt( );
String myStr = in.next( );
Constructors: used to initialize objects
•
Research has
found that a very common error in programs is for variables or objects to have
unknown values
•
Constructors give
objects initial values, which then the user can change if they wish
•
Constructors always have the same name as the class
•
They never have a return type
•
The constructor
is called when the object is created, initializing it.
•
There can be more
than one constructor for a class
•
The difference
between them is the number of arguments they have.
Examples of the interactive I/O and a
constructors will be found
On the files that are linked to the lecture page.