Presentation is loading. Please wait.

Presentation is loading. Please wait.

FIT1002 2006 1 Objectives By the end of this lecture, students should: understand the structure of a class understand the concept of a method understand.

Similar presentations


Presentation on theme: "FIT1002 2006 1 Objectives By the end of this lecture, students should: understand the structure of a class understand the concept of a method understand."— Presentation transcript:

1 FIT1002 2006 1 Objectives By the end of this lecture, students should: understand the structure of a class understand the concept of a method understand the difference between normal variables and instance variables understand basic visibility issues be able to code simple classes

2 FIT1002 2006 2 Implementation of a Class The Java code that implements a class has the following structure: class className { Declaration of attributes Definitions of methods } Terminology: Attributes are also known as Instance Variables, Fields, or Properties.

3 FIT1002 2006 3 Comments class Person /* This class implements a person for the customer database. author: Dianne Hagen, last change: 2/1/06, Bernd Meyer */ { // instance variables (attributes) String name;... You should always comment your code so that every reader (including yourself a year later) can understand what is intended. Comments in Java are delimited by “//” for a single line and by the comment brackets “/*” and “*/” for multi-line.

4 FIT1002 2006 4 Declaring Attributes class Person { // instance variables (attributes) String name; int age; boolean isStudent; // currently this class has no methods }

5 FIT1002 2006 5 Instance Variables can be Object-valued class Person { // instance variables (attributes) String name; Person partner; int age; boolean isStudent; // currently this class has no methods } We have already seen that a variable can either hold a basic data type or an object (e.g. a String). The same is true for instance variables (see partner above).

6 FIT1002 2006 6 Creating an Instance Each instance must be explicitly created with a “new” statement: new Person(); Of course, if you want to later use this instance, you need to keep it somewhere. In BlueJ it will exist on the workbench, but to use it in a Java program you need to give it a name. Technically speaking, you need to create a variable of appropriate type and bind the new instance to it. Person bestFriend; bestFriend = new Person(); This can be done in a single statement: Person bestFriend = new Person();

7 FIT1002 2006 7 Accessing Attributes Directly Instance attributes (if declared as above) can be accessed directly via the instance. For this we use the “dot Notation”: Person bestFriend = new Person(); bestFriend.name = “Harvey”; bestFriend.age = 40; Person p; p = bestFriend; p.age = 99; int bestFriendsAge = bestFriend.age System.out.println(bestFriendAge);

8 FIT1002 2006 8 Visibility (Private / Public) In most circumstances, instance variables should only be directly accessible to the instance itself. To do this they must be declared as private. class Person { // instance variables (attributes) // now private private String name; private Person partner; private int age; private boolean isStudent; // currently this class has no methods }

9 FIT1002 2006 9 Visibility (Private / Public) Any attempt to access a private attribute from outside of the declaring class will lead to an error: Person bestFriend = new Person(); bestFriend.name = “Harvey”; in BlueJ >> “ Error: age has private access in Person” in Java Compilation >> “Cannot find symbol - name” class Person { // instance variables (attributes) // now private private String name;… }

10 FIT1002 2006 10 Visibility (Private / Public) However, usually this has to be avoided as we lose all access control in the defining class. Generally, this should be considered as unsafe and attributes should be declared private whenever possible. To gain access to “private” instance variables from the outside, we will define get and set methods (accessor and mutator methods, see below), which allow us to explicitly manipulate the instance variables. class Person { // instance variables (attributes) // now private public String name;… } We can declare an instance variable to be accessible without restriction. This is done by declaring it as public.

11 FIT1002 2006 11 Visibility (Pitfall) Advanced topic, optional (Encapsulation and Inheritance) there is a pitfall with declaring attributes as private when using inheritance: Let “Student” be a subclass of “Person”. Let “Person” have some private attribute, say “name” “Student” will not be able to access “name”. As this usually contradicts the idea of inheriting, you need to declare attributes differently in this situation. Declaring “name” as “public” works, but is dangerous. A somewhat safer way is to not use either modifier as we have done on Slide 5. This is called “package” access. It will allow “Student” to see the “name” attribute, but still offer some level of access protection. In the context of FIT1002 “package” and “public” access are identical. If you want to inherit an attribute you can use either of these. For details, see Savitch p 448-453. Warning: you need to understand “Packages” for this (Savitch, Sec. 5.4)

12 FIT1002 2006 12 Get / Set Methods Get/Set Methods are one of the simplest types of methods Get Methods (accessors) return the value of a specific instance variable. Set Methods (mutators) set the value of a specific instance variable to a value that is given in the method call.

13 FIT1002 2006 13 Methods A Method implements a pre-defined behaviour for an object. A method can effect a change (e.g. change an attribute, print something) return an answer (e.g. whether a person is of legal age) both of the above.

14 FIT1002 2006 14 A Method without Parameters and Results public void display() { System.out.println("My name is " + name + " and I am " + age + " years old."); } This method is invoked by the expression: bestFriend.display();

15 FIT1002 2006 15 Structure of a Method The first line of the method is the header. The rest of the method (delimited by curly braces) is the body. int getAge() { return age; } The header shows who can access this method, what type of data it returns, its name, and what other information it needs(in the case of getAge(): nothing). This is the information you need in order to be able to invoke it. The body is the set of instructions that tell the computer how to do the job this method is designed to do.

16 FIT1002 2006 16 Returning a Value from a Method name age getName "Jack" bestFriend In Java we use the return statement to send back a value to the object that asked for it. The Java code inside the getName method in the Person class ends with: return name; name is the variable that holds the current value of that attribute of the object bestFriend.

17 FIT1002 2006 17 The return Statement The return statement in a method does two things: it sends back a value to the calling method it causes the execution of its own method to be terminated immediately This means that, if a method executes a return statement, nothing in the same method will be executed after it.

18 FIT1002 2006 18 get Methods public int getAge() { return age; } public String getName() { return name; } public boolean getStudentStatus() { return isStudent; } get methods are also known as accessor methods.

19 FIT1002 2006 19 set Methods public void setAge(int newAge) { age = newAge; } public void setName(String newName) { name = newName; } public void setStudentStatus(boolean aStudentStatus) { isStudent = aStudentStatus; } set methods are also known as mutator methods.

20 FIT1002 2006 20 Method Parameters and Calls public void setAge(int anAge) { age = anAge; } This method needs to know what the new value of age is to be. We give it that information in the call. bestFriend.setAge(18); Which parameters the method expects in a call is defined in the method header. Look at the BlueJ prompt when you invoke this method.

21 FIT1002 2006 21 Calling Another Method in the Same Class In the Person class: public void display() { System.out.println(toString()); } public String toString() { return name + " is " + age + " years old"; }

22 FIT1002 2006 22 Calling a Method in a Different Class public boolean setName(String aName) { if (validName(aName)) { name = aName; return true; } return false; } public boolean validName(String aName) { return !isEmptyOrBlank(aName); } public boolean isEmptyOrBlank(String aString) { return aString.trim().length() == 0; }

23 FIT1002 2006 23 Complete Class Diagram for Person Class Person name: String age: int isStudent: boolean display() getAge(): int getName(): String getStudentStatus(): boolean setAge(int): boolean setName(String): boolean setStudentStatus(boolean) validAge(int): boolean validName(String): boolean

24 FIT1002 2006 24 Visibility (Classes and Methods) The same access modifiers as for instance variables can be applied to classes and methods. In the context of FIT1002 we will always declare classes as public (nothing else makes sense in the part of the language we handle) we will (almost) always declare methods as public, as we usually want to be able to call them from outside. The access rules for private methods are the same as for private attributes, ie. they can only be called from within the class.

25 FIT1002 2006 25 Instance Variables vs. Method Variables public class InterestCalculator { private double interestRate; private double balance; public void initialize() { interestRate = 5; balance = 1000; } public double calculateInterest() { double interest; interest = balance * interestRate / 100; return interest; } Attributes method variable

26 FIT1002 2006 26 Local Variables The entire body of a method is a block. A variable defined inside the body of a method is called a method variable or a local variable (e.g. the variable interest on the previous slide). A variable declared at the beginning of a method has a scope of the entire body of the method. No other method can refer to that variable. A variable can be declared anywhere inside a method. Its scope is from where it is declared to the end of its block.

27 FIT1002 2006 27 Scoping The scope of a method or a variable is the part of a program that can access it (“see it”). We limit the scope of variables and methods as much as possible, to reduce the chance of error in a program. Some kinds of scoping that we have already seen in programs are: class scope block scope

28 FIT1002 2006 28 Class Scope All attributes and methods have class scope. This means that any statement inside the class declaration can access them. The class declaration is delimited by the set of braces around the class. Any attribute can be referred to or modified by any statement in any method in the class (e.g. interestRate above). Any method can be called by any statement in any method in the class.

29 FIT1002 2006 29 Block Scope A variable declared inside a block (a local variable or method variable like interest above) has block scope. It exists only inside that block, only while that block is being executed. Statements outside that block cannot reference it. Some examples of blocks are: the body of a method a compound statement that is the consequent or alternative of an if statement the body of a loop an area of a method delimited by a set of braces { }. A block can be placed anywhere in the code.

30 FIT1002 2006 30 Lexical Scoping Blocks are a lexical concept. This means that area of a block (and thus the associated scope) can be determined from looking at the “program listing” without taking its execution into account. A piece of code consists of nested blocks:

31 FIT1002 2006 31 Referencing a Variable Outside Its Block public String inputStudentIdOrName() { if (isStudent) { Scanner input = new Scanner(System.in); System.out.println("What is your ID number?"); return input.nextLine(); } else { System.out.println("Not a student"); System.out.println(What is yoru name?"); return input.nextLine(); } This produces a compilation error: cannot find symbol - variable input

32 FIT1002 2006 32 Correct Version of inputStudentId public String inputStudentIdOrName() { Scanner input = new Scanner(System.in); if (isStudent) { System.out.println("What is your ID number?"); return input.nextLine(); } else { System.out.println("Not a student"); System.out.println(What is yoru name?"); return input.nextLine(); }

33 FIT1002 2006 33 Local Variables in Loops public void localLoop() { for (int i=0; i<5; i++) System.out.println("in "+i+"-th iteration: "+i); System.out.println("after loop: "+i); } A common use for local variables is in for -loops. If the declaration is performed in the for -header the variable will be local to the loop body, as the loop implicitly established a new block. The following code will not compile, because “i” is local to the loop:

34 FIT1002 2006 34 Declaration in Middle of Block public void inputDetails() { System.out.println("What type of account would you like?"); System.out.println("1. Savings"); System.out.println("2. Cheque"); Scanner input = new Scanner(System.in); int choice = input.nextInt(); if (choice == 1) accountType = "Savings"; else if (choice == 2) accountType = "Cheque"; else System.out.println("Choose 1 or 2"); theClient.inputDetails(); }

35 FIT1002 2006 35 Scope of Formal Parameters A formal parameter (a parameter in the method header) is created at the time its method is called. It is given an initial value of whatever corresponding value is passed on the call. The scope of a formal parameter is the body of its method. It exists only while that method is executing, and can be accessed only by statements inside that method. As soon as the method finishes executing, the memory for the formal parameter is released.

36 FIT1002 2006 36 Variables with the Same Name If we have two variables with the same name and the same scope, we get a syntax error. We can, of course, use the same name for two variables if their two scopes have no overlap (it is then always well defined to which variable the name refers). Example: a local variable in one method that is passed to another method with a formal parameter of the same name.

37 FIT1002 2006 37 Formal Parameter and Actual Argument with Same Name public boolean setName(String aName) { if ( validName(aName) ) { name = aName; return true; } return false; } public boolean validName(String x) { return !isEmptyOrBlank(x); }

38 FIT1002 2006 38 Formal Parameter and Actual Argument with Same Name public boolean setName(String aName) { if (validName(aName)) { name = aName; return true; } return false; } public boolean validName(String aName) { return !isEmptyOrBlank(aName); }

39 FIT1002 2006 39 Masked or HiddenVariables If more than one variable with the same name is accessible from a part of a program, a mention of that name will access the one that is closest in scope. This may have unintended effects. Consider the following methods in the class Person. Recall that Person has an instance variable name. What effect does the marked statement have on toString() ? public void display() { System.out.println(toString()); } public String toString() { String name = "Fred"; return (name + “ is " + age + “ years old”); }

40 FIT1002 2006 40 Using Two Variables of the Same Name with Different Scopes It is possible (but often not advisable) to use a formal parameter name, for example, that is the same as an attribute, and to use both in the same method. public boolean setAge(int age) { if (validAge(age)) { this.age = age; return true; } return false; } You then have to use this.name to refer to the instance variable. Formal parameter Instance variable

41 FIT1002 2006 41this this is a keyword that means "the current object", i.e. the one that is currently in control, which has been asked to invoke this method. It is possible to write this in front of anything with class scope, i.e. any attribute or method name. public void setAllAttributes(String aName, int anAge, boolean aStudentStatus) { this.name = aName; this.age = anAge; this.isStudent = aStudentStatus; } but it is not necessary unless you need to clarify the scope.

42 FIT1002 2006 42 Calling Methods with “this” You could also write this in front of any call to another method in the same class, if you wanted to be pedantic about always putting the name of an object in front of a call. The object you are asking to invoke the method is yourself. public void display() { System.out.println(this.toString()); }


Download ppt "FIT1002 2006 1 Objectives By the end of this lecture, students should: understand the structure of a class understand the concept of a method understand."

Similar presentations


Ads by Google