objectives
play

Objectives become familiar with the concept of a class Defining - PDF document

Objectives become familiar with the concept of a class Defining Classes and Methods an object that instantiates the class learn how to Chapter 4 define classes define and use methods create objects use


  1. Objectives • become familiar with the concept of – a class Defining Classes and Methods – an object that instantiates the class • learn how to Chapter 4 – define classes – define and use methods – create objects – use parameters in methods Objectives, cont. Outline • learn about • Class and Method Definitions – information hiding and encapsulation • Information Hiding and Encapsulation – the notion of a reference • Objects and Reference • understand class variables and class parameters Basic Terminology What does a class have? • A class defines a kind of objects: • Members of a class : – Attributes (instance variables, data) – specifies the kinds of attributes ( data ) an • For each instance of the class (object), values of attributes can object of the class can have. vary, hence instance variables – Methods – provides methods specifying the actions an • Person class object of the class can take. – Attributes: name, address, phone number • An object is an instance of the class. – Methods: change address, change phone number • Alice object • Person is a class – Name is Alice, address is … • Bob object – Alice and Bob are objects of the Person class. – Name is Bob, address is … 1

  2. A Class as an Outline A UML Class Diagram The Method main Method Definitions • Methods belong to a class • A program – Defined inside the class – a class that has a method named main . • Heading – Execution begins in the main method – Return type (e.g. int, float, void ) • So far – Name (e.g. nextInt, println ) – Parameters (e.g. println(…) ) – no attributes (instance variables) – More… – no methods other than method main . • Body – enclosed in braces {} . – Declarations and/or statements. ------------ Person.java ------ defining Person --------------------- public class Person { private String _name; Example private String _iceCream; public void setName(String newName) { this._name = newName; // this. is optional } • class SpeciesFirstTry public void setIceCream(String newIceCream) { … } public void print() { System.out.println(this._name + “ likes “ + this._IceCream); // this. optional } } ------------ PersonTest.java ----- using Person ------------------ public class PersonTest { public static void main(String[] args) { Person joe = new Person(); joe.setName(“Joseph”); joe.setIceCream(“Rocky Road”); Person mary = new Person(); mary.setName(“Mary”); mary.setIceCream(“Chocolate Fudge”); mary.print(); } } 2

  3. Example, contd. Class Files and Separate Compilation • class SpeciesFirstTryDemo • One class definition per file • File name and class name are the same – File extension is .java • After compilation – byte code is stored in a file with extension .class • Execution – .class is run in the JVM • Multiple .class files in the same directory – Each object of type SpeciesFirstTry has its – No need to import them own values for the three attributes void Method Definitions Two Types of Methods 1. Return a value • example public void writeOuput() //heading – next = keyboard.nextInt(); { //body keyboard is the calling object. – System.out.println(“Name: “ + name); 2. Don’t return a value, called void method System.out.println(“Age: “ + age); } – System.out.println(“Enter data:”); System.out is the calling object – Using return in a void Defining Methods That Return Method a Value • form • example return; public float density(float area) // heading { // body • usage return population / area; – end the invocation of the method } prematurely for dealing with some problem • caution – better ways to deal with a potential problem (“exceptions”) [later...] 3

  4. Defining Methods That Return Naming Methods a Value, cont. • Use a verb to name methods • must contain return statement – Actions return Expression ; – getBalance, deposit, changeAddress – Expression must have a type that matches • Start a method name with a lowercase letter. the return type • multiple return statements are allowed – a single return statement is better (one exit point for the method). public Method Definitions public Method Definitions • syntax for a void method • syntax for methods that return a value public void methodName ( parameters ) public returnType methodName ( parameters ) { { < statement(s) > < statement(s), including a } return statement > } Example Using this Accessing Attributes • Defining the writeOutput method • Inside the definition of the same class – <attributeName> or public void writeOutput() this.<attributeName> { System.out.println("Name = " + this .name); – name = “Lara”; or System.out.println("Population = " + this._name = “Lara”; this .population); • Outside the class definition System.out.println("Growth rate = " + this .growthRate + "%"); – i.e. in another class definition } – <objectName>.<attributeName> • Using the writeOutput method – myBestFriend._name = “Lara”; – tiger.writeOutput() • this refers to the tiger object – Not recommended, later… 4

  5. Example Using this Local Variables • Defining the addPopulation method : • Declared within a method – “local to” (confined to) the method public int addPopulation(SpeciesFirstTryDemo species2) definition { – can’t be accessed outside the method return this .population + species2.population; } • Not attributes (instance variables) • Using the addPopulation method – tiger.addPopulation(lion) • this refers to the tiger object • species2 refers to the lion object Local Variables, cont. Blocks • class BankAccount • class LocalVariablesDemoProgram • Block and compound statement – a set of Java statements enclosed in braces {} . • Variable declared within a block – local to the block. – when the block ends, the variable “disappears.” • Variable declared outside multiple blocks – spanning multiple blocks Scope of a local variable Example of Scope public void method1() { // begin of block int x; • The region in the program where the if (…) local variable can be accessed { // begin of block int y; // can’t have int x here, confusing anyway … – Start: declaration of the variable } else { // begin of block – End: the closing } of the block in which the … // can y be used here? } variable is declared … // can y be used here? } public int method2() { // begin of block int x; // can I do this? … return x; } 5

  6. Variables in for Statements Example of Scope public void method() • Variable declared outside the for statement { for (int i=0; i < 10; i++) // start of a block int n; { for (n = 1; n <10; n++) {…} int y=0; – variable n still exists when the for … statement ends } • Variable declared inside the for statement // Are i and y accessible here? } for (int n = 1; n <10; n++) {…} – variable n disappears when the for statement ends Passing Values to a Method: Formal vs Actual Parameters Parameters • Input values for methods (within the program, not from user) public static void main(String[] args) – passed values or parameters { • More flexibility for methods print(“George Bush”); • formal parameters } – Part of method definition – After the method name, within parentheses public static void print(String name) • type { • name System.out.print(“The name is: “ + name); • arguments , or actual parameters } – Calling a method with an object within the parentheses • matching data type • in the same order Parameter Passing Example Scope of Formal Parameters //Definition of method to double an integer public int doubleValue(int numberIn) { • Start: begin of the method return 2 * numberIn; } • End: end of the method public float square(float num) //Invocation of the method... somewhere in main... { // begin of num’s scope ... int next = keyboard.nextInt(); … System.out.println(someObj.doubleValue(next)); } // end of num’s scope • What is the formal parameter in the method definition? – numberIn • What is the argument (actual parameter) in the method invocation? – next 6

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend