Programming in Java Transitioning from Alice Becomes not
Programming in Java Transitioning from Alice
Becomes not my. First. Method 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 Use. Bunny 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 give. Color. Info() { return color; } public int give. Age. Info() { return age; }
Modifier Methods // modifier methods – change properties public void set. Color (String new. Color) { color = new. Color; } public void set. Age (int new. Age) { age = new. Age; } }
Use. Bunny. java Revisited class Use. Bunny{ public static void main(String[] arg) { Bunny b = new Bunny(); //like add Object Bunny b 1 = new Bunny(); b. set. Age(6); b 1. set. Color("green"); System. out. println("The first bunny is : "); System. out. println(b. give. Age. Info() + " and is " + b. give. Color. Info()); System. out. println("The second bunny is : "); System. out. println(b 1. give. Age. Info() + " and is " + b 1. give. Color. Info()); } }
Java Assignment 1 – Part 1: Make the Lab 1 project and run the First. One Java program Part 2: Make the Lab 1 Pt. II project and get the Use. Bunny and Bunny to work
- Slides: 19