CPSC 233 Tutorial 5 February 9 th /10 th, 2015
Java Classes Each Java class contains a set of instance variables and methods Instance Variables: Type + Name Each object of a class has its own copy of the class instances.
Java Instance Variables public class SpeciesSecondTry { public String name; public int population; public double growthRate; public void writeOutput () { … } public int PredictPupulation (int years) { … }
Java Methods A method contains: Heading Name A method is invoked by its name Output Type Input Type Name Body Block {} Local Variables A series of statements defining the method functionality
Java Methods Output A method of a class should be invoked to: Return a value Perform a task without returning a value
Method Without Output Methods without Output Use the keyword void Perform some operations such as printing or changing the value for an instance variable within its block
Method With Output Method with output Define the type of output Use the keyword return to return the output
Method Input Input parameters (Formal parameters) serve as a blank space in the method These blank spaces are considered local variables for the method Input types: Primitive Types Byte – Short – Int – Long – Float – Double – Char Is String a primitive? Reference to an object Class name + Object name
Method Input Cont. When invoking a method using arguments, your arguments should have the same number, order and type as your formal parameters. Invoking PredictPopulation method:
Exercise Write a Dog class in Java with following characteristic: This class has one instance variable: Name An object of this class should be able to perform following operations: Set values for instance variable. Take the dog age as a primitive parameter and calculate the human age. Print out the instance variables and human age
Exercise Solution
Exercise cont. Write a class to test your Dog calss
Class Test
References Course Slides JAVA, An introduction to problem solving and programming