Transcript Document

Programming in Java
Transitioning from Alice
Becomes not myFirstMethod but ….
public static void main (String[] arg)
{
}
// code for testing classes goes here
Your project and classes are similar
Both functions and methods
are referred to as methods
in Java
void methods are methods
which do not return values
Methods with “return types” are
often referred to as functions – just as
in Alice, they can return numbers
(called int or doubles),
booleans, Strings, or Objects
Properties in Java are referred to
as private instance variables
Simple Programs
Very simple program to print a name
Simple program to test a separate class
and instantiated objects
Output from Play
Java from Eclipse
main method
Running it
Output
Bunny and UseBunny
Create a Bunny class
Properties : color and age
Modifier methods to change those properties
Accessor methods to return those properties
Special method of reach class used to create
the instances – called constructor
Constructor and Instance
Variables
class Bunny {
//In Java need a constructor for every new class
public Bunny() //set default properties
{
age = 0;
color = "white";
}
//private instance variables (like properties)
int age;
String color;
Accessor Methods -- usually
functions
//accessor methods
public String giveColorInfo()
{
return color;
}
public int giveAgeInfo()
{
return age;
}
Modifier Methods
// modifier methods – change properties
public void setColor (String newColor)
{
color = newColor;
}
public void setAge (int newAge)
{
age = newAge;
}
}
UseBunny.java Revisited
class UseBunny{
public static void main(String[] arg)
{
Bunny b = new Bunny(); //like add Object
Bunny b1 = new Bunny();
b.setAge(6);
b1.setColor("green");
System.out.println("The first bunny is :");
System.out.println(b.giveAgeInfo() + " and is " + b.giveColorInfo());
System.out.println("The second bunny is :");
System.out.println(b1.giveAgeInfo() + " and is " + b1.giveColorInfo());
}
}
Java Assignment
Java Assignment 1 –
Part 1:Make the Lab1 project and run the
FirstOne Java program
Part 2: Make the Lab1PtII project and get the
UseBunny and Bunny to work