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.

Slides:



Advertisements
Similar presentations
Looking inside classes Fields, Constructors & Methods Week 3.
Advertisements

Based on Java Software Development, 5th Ed. By Lewis &Loftus
Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
The Fundamental Rule for Testing Methods Every method should be tested in a program in which every other method in the testing program has already been.
Variable types We have already encountered the idea of a variable type. It is also possible to think about variables in terms of their kind, namely: 1)
Defining classes and methods Recitation – 09/(25,26)/2008 CS 180 Department of Computer Science, Purdue University.
Road Map Introduction to object oriented programming. Classes
19-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
25-Jun-15 Starting Classes and Methods. Objects have behaviors In old style programming, you had: data, which was completely passive functions, which.
Information Hiding and Encapsulation
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Understanding class definitions Looking inside classes.
COMP More About Classes Yi Hong May 22, 2015.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Writing Classes (Chapter 4)
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
The Java Programming Language
Classes CS 21a: Introduction to Computing I First Semester,
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Introduction to programming in the Java programming language.
Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???
CPS120: Introduction to Computer Science Lecture 14 Functions.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
JAVA Classes Review. Definitions Class – a description of the attributes and behavior of a set of computational objects Constructor – a method that is.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA ‏ Visibility Control.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
1 Programming Week 2 2 Inheritance Basic Java Language Section.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
CSE 1301 Lecture 6 Writing Classes Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams.
Chapter 5 Introduction to Defining Classes
IT108 Objects and Classes Part I George Mason University Revised 4/3/2012.
24-Dec-15 Class Structure. 2 Classes A class describes a set of objects The objects are called instances of the class A class describes: Fields (instance.
Chapter 3: Developing Class Methods Object-Oriented Program Development Using Java: A Class-Centered Approach.
CIT 590 Intro to Programming Lecture 13. Some Eclipse shortcuts CTRL + SHIFT + F – format file (proper indentation etc). Please do this before you submit.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Slide 1 Chapter 6 Structures and Classes. Slide 2 Learning Objectives  Structures  Structure types  Structures as function arguments  Initializing.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
CS 116 Lecture 1 John Korah Contains content provided by George Koutsogiannakis & Matt Bauer.
FIT Objectives By the end of this lecture, students should: understand the role of constructors understand how non-default constructors are.
Understanding class definitions Exploring source code 6.0.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Class Structure 15-Jun-18.
Some Eclipse shortcuts
Java Primer 1: Types, Classes and Operators
Classes.
Class Structure 16-Nov-18.
Corresponds with Chapter 7
Defining Classes and Methods
Creating Objects in a Few Simple Steps
Class Structure 28-Nov-18.
Class Structure 7-Dec-18.
Class Structure 2-Jan-19.
Chapter 4 Topics: class declarations method declarations
Class Structure 25-Feb-19.
Java Programming Language
Defining Classes and Methods
Classes, Objects and Methods
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
References Revisted (Ch 5)
Review for Midterm 3.
Presentation transcript:

FIT 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

FIT 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.

FIT 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.

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

FIT 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).

FIT 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();

FIT 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);

FIT 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 }

FIT 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;… }

FIT 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.

FIT 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 Warning: you need to understand “Packages” for this (Savitch, Sec. 5.4)

FIT 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.

FIT 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.

FIT 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();

FIT 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.

FIT 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.

FIT 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.

FIT 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.

FIT 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.

FIT 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.

FIT 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"; }

FIT 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; }

FIT 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

FIT 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.

FIT 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

FIT 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.

FIT 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

FIT 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.

FIT 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.

FIT 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:

FIT 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

FIT 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(); }

FIT 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:

FIT 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(); }

FIT 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.

FIT 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.

FIT 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); }

FIT 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); }

FIT 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”); }

FIT 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

FIT this 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.

FIT 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()); }