Presentation is loading. Please wait.

Presentation is loading. Please wait.

Class Definitions and Writing Methods Chapter 3 10/12/15 & 10/13/15 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education.

Similar presentations


Presentation on theme: "Class Definitions and Writing Methods Chapter 3 10/12/15 & 10/13/15 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education."— Presentation transcript:

1 Class Definitions and Writing Methods Chapter 3 10/12/15 & 10/13/15 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010

2 Announcements Remove 3.5 and 3.6 from last week's Zybooks assignment. Icelandic Flag, Program 4, due next week. Chapter 3 covers static methods. For now I will just cover class member methods. You still need to read the examples to better understand writing methods, in general, using parameters and returning a value.

3 Objectives Given a description a class, list its data fields and methods. Write a class once you have decided what its data fields and methods are. Describe the use of the access modifiers public and private. Write a method definition. Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010

4 Objectives Write methods that use parameters. Write constructors Describe the use of accessor methods and mutator methods, and write their definitions. Call a method given its header. Describe the effect of a given call to a method. Write a class definition. Write a driver to test the class. Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010

5 Objects Have Data Have Methods  Things the object can do. Example – Clock  Data?  Methods? Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010

6 Get with Partner Think of an object. What data and methods would it have?

7 Classes Are Types We have used classes such as Scanner and JFrame. The class is a type we can use to instantiate, or create, objects. The classes have data and methods associated with them.  e.g. nextDouble( ) is a method of Scanner.  A JFrame has a length and width.

8 Designing a Class To design a class, first decide what data the class will have and what methods it will have. For example: A SimpleDate class.

9 A SimpleDate Class A SimpleDate class is needed store a date. It should know how to print the date in either U.S. or European style. Design this class. – Tell what data fields and methods it needs

10 Design a Class With your partner design a SSN class to represent a Social Security number. You can decide how to store the number. It needs to be able to print the number as ######### Or ###-##-####

11 Implement Class SimpleDate Make a class without a main(). Put datafields at top of class, outside of any method Methods are like small versions of the main method. Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010

12 Defining the Class Fields: month, day, year a)Declared within a class b)private c)Allocated within an object of the class d)Each object has its own month, day and year data fields. e)Data fields also called instance variables. Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010

13 Defining the Class Methods – define the class' behaviors. printUS(), printEU() setMonth, setDay(), setYear() Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010

14 Method Syntax access-modifier return-type method-name(optional-parameter-list) { statement(s); }  Access modifiers are public and private.  Methods are usually public

15 Referencing Instance Variables The data fields of the class. They can be referred to by any method. If a SimpleDate, sd, is named in a call to a method, sd.printUS(), the fields belonging to sd are affected. Let’s write the printUS() method.

16 Driver to Test SimpleDate Need a program to test the class. Instantiate some SimpleDates and make sure all of the methods I wrote work correctly. I can do incremental testing.

17 Setters Now I need some setters to set the mo, day, year. SetMonth( ), setDay( ), setYear( ) They have parameters store the values passed to them. We will use the values to initialize the data fields.

18 public class SimpleDate { private int day; private int month; private int year; public void setDay(int d){ day = d; } public void setMonth(int m){ month = m; } public void setYear(int y){ year = y; } public void displayUS(){ System.out.println(month + "/"+ day + "/" + year); }

19 public class TestSimpleDate { public static void main(String[] args){ SimpleDate sd1 = new SimpleDate(); //Test the methods for the class }

20 Participation Copy my SimpleDate class and driver Write the printEU( ) method.

21 Another Example

22 Parameters and Arguments In sd.setMonth(11); 11 is an argument.  It is a value that is passed to a Method. The method needs to receive this argument and store it.  It uses a parameter.  A parameter is a dummy variable that waits for a value to be passed into it.  Parameters are declared inside of the parenthesis in the method header.

23 StoreSale Class A clothing store wants a StoreSale class to help with its sales. It has sales where there is a certain storewide discount, like 20% off everything.

24 StoreSale Class A store sale stores the discount rate. For example for April 15 th they are having a tax return sale at 15% off. StoreSale taxDaySale = new StoreSale( ); taxDaySale.setRate(15 );

25 StoreSale Class To find a discounted price on an item the price is send to a findSalePrice() method: Double salePrice = taxDaySale.findSalePrice(60.00);

26 Data and Methods for the Class?

27 Start the Class The class name is StoreSale. Write the setter.

28 Local Variable Variable that is declared inside { }, in a block of statements. It can only be used in that block of statements. findSalePrice() could have a local variable. Let’s start the method

29 Returning a Value If a method needs to get a value back to where it is called, it returns a value via the return statement. – return x; The findSalePrice method needs to tell us the sale price, so it needs a return statement.

30 Parameters Are Local Parameters act like local variables in a method.

31 More Special Methods

32 Data fields are hidden to protect them.  The data is private Accessor methods, the “getters”.  Accessor lets outside methods access, or get, a data field's value. Name usually starts with "get". Returns the private data. Mutator methods, the “setters”, l et outside methods change a value. Name usually starts with "set". Changes the private data. Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010

33 More Special Methods I'll add a getter to the StoreSale class. Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010

34 Questions In the following Dog class identify: 1. The data field. 2.The accessor and mutator methods. 3. A local variable. 4. A parameter. 5.What is the output of the driver?

35 //Dog class public class Dog { private int years; public Dog(){ years = 0; } public Dog(int y){ years = y; } public int getYears(){ return years; } public void setYears(int y){ years = y; } public int dogYears(){ int dy; dy = years *7; return dy; }

36 //Dog Driver -- What is the output? public class DogDriver{ public static void main(String args[]){ Dog bella = new Dog(); // Make a dog, no age bella.setYears(5); System.out.println("Bella: "); System.out.println(bella.getYears()+ " years."); System.out.println(bella.dogYears()+ " dog years"); }

37 More on Classes Commenting classes this pointer

38 Comments in Classes Each class should have a description. Each method within a class should have a comment. Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010

39 The this pointer Allows an object to reference itself. It can be used when a local variable has the same name as a field does. The local name dominates. Some programmers also use it to make code clearer.

40 The this pointer e.g. Dog bella = new Dog(); // Make a dog, no age bella.setYears(5);

41 public class Dog{ private int years; //Name conflict with “years” public void setYears(int years){ years = years; } //Use “this” to fix name conflict public void setYears(int years){ this.years = years; }

42 this We will cover its use in constructors later.

43 Static Methods Method that can be called without creating an object. Can not use data fields. Can get data passed through parameters. Example – convertToMiles method to convert kilometers to miles.

44 Participation Make getters for the datafields in the SimpleDate class that we created last week. If you weren't here, make both getters and setters for the data fields.

45 More Linux Commands mkdir rmdir echo mv file, directory mv oldFileName newFileName more file

46 Notes

47 Constructors-Later (Skip the Rest of PowerPoint) Later In Chapter 9

48 Participation Sphere class Design class called Sphere that stores its radius. A Sphere will be able to print its area and volume. What are the data fields and methods of a Sphere? Work with a partner. Write a paper copy.

49 SimpleDate with default value A method to initialize a SimpleDate is usually provided. What do you call a method that is called when an object is created?

50 Special Methods Constructor methods – Have the same name as the class. – Instantiate new Object – Initialize Object's fields  Intialize means to give it a starting value. – A default constructor accepts no arguments. May initialize the field(s) to a default value. Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010

51 Putting Constructors in the SimpleDate Class A constructor's name is the same as the class name. In this case I will make two:  Default constructor – sets month, day and year to default values  Parameterized constructor – sets month, day and year to values passed.

52 Constructor Syntax access-modifier class-name(optional-parameter-list) { statement(s); }  Access modifiers must be public on a Constructor  Constructor do not have a return type.

53 Default Constructor Hints In absence of programmer defined constructor  Java will provide default constructor Good practice to specify default values for data fields Don’t duplicate tasks  Methods should call each other Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010

54 Participation 2 Login and begin a Sphere class. Code the methods to find area, find volume and set the radius. Write a default constructor and a parameterized constructor for it.

55 Participation 2 A Driver The class must be tested. Need to write a program to create a Sphere or two. The constructors can be tested by using the new operator. Test all of the methods.

56 Class Definitions and Writing Methods: Chapter 3 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010


Download ppt "Class Definitions and Writing Methods Chapter 3 10/12/15 & 10/13/15 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education."

Similar presentations


Ads by Google