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.

Slides:



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

Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-3: Encapsulation, toString reading: self-checks: #13-18,
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
***** SWTJC STEM ***** Chapter 4-1 cg 42 Object Oriented Program Terms Up until now we have focused on application programs written in procedural oriented.
Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
Road Map Introduction to object oriented programming. Classes
1 Classes Overview l Classes as Types l Declaring Instance Variables l Implementing Methods l Constructors l Accessor and Mutator Methods.
Classes and Objects April 6, Object Oriented Programming Creating functions helps to make code that we can reuse. When programs get large it becomes.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
1 Fall 2007ACS-1903 Chapter 6: Classes Classes and Objects Instance Fields and Methods Constructors Overloading of Methods and Constructors Scope of Instance.
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Methods and Constructors reading: self-checks: #1-12.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors reading:
Classes and Class Members Chapter 3. 3 Public Interface Contract between class and its clients to fulfill certain responsibilities The client is an object.
Writing Classes (Chapter 4)
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals; Apply data abstraction.
Writing Classes You have already used classes –String, Random, Scanner, Math, Graphics, etc –To use a class: import the class or the package containing.
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.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
CSC 142 Computer Science II Zhen Jiang West Chester University
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors, Encapsulation, this reading:
A First Look at Java Chapter 2 1/29 & 2/2 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Copyright © 2012 Pearson Education, Inc. Chapter 9 Classes and Multiform Projects.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
CSC 142 Computer Science II Zhen Jiang West Chester University
Java - Classes JPatterson. What is a class? public class _Alpha { public static void main(String [] args) { } You have been using classes all year – you.
More about Java Chapter 2 9/8 & 9/9 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
CS0007: Introduction to Computer Programming Classes: Documentation, Method Overloading, Scope, Packages, and “Finding the Classes”
Introduction Chapter 1 8/31 & 9/1 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
Methods: A Deeper Look. Template for Class Definition public class { } A.Import Statement B.Class Comments C.Class Name D.Data members E.Methods (inc.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
Classes Modeling the Object. Objects model the world Classes are programmer defined types that model the parts of a system Class serve as blueprints for.
Chapter 4 10/26 & 10/27. More Linux Commands mkdir rmdir echo > redirect output mv file, directory mv oldFileName newFileName more file rm file.
CSci 162 Lecture 10 Martin van Bommel. Procedures vs Objects Procedural Programming –Centered on the procedures or actions that take place in a program.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 9 Objects and Classes.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
Java Programming, Second Edition Chapter Three Using Methods, Classes, and Objects.
CS 116 Lecture 1 John Korah Contains content provided by George Koutsogiannakis & Matt Bauer.
Attribute - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 12/24/2016.
Topics Instance variables, set and get methods Encapsulation
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
OOP Basics Classes & Methods (c) IDMS/SQL News
Comp1004: Building Better Objects II Encapsulation and Constructors.
Class Definitions and Writing Methods Chapter 3 3/31/16 & 4/4/16.
Class Definitions: The Fundamentals Chapter 6 3/30/15 & 4/2/15 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education.
Programming in Java Transitioning from Alice. Becomes not myFirstMethod but …. public static void main (String[] arg) { // code for testing classes goes.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors, Encapsulation, this reading:
Objects as a programming concept
Review What is an object? What is a class?
Class Definitions and Writing Methods
Multiple if-else boolean Data
HKCT Java OOP Unit 02 Object Oriented Programming in Java Unit 02 Methods, Classes, and Objects 1.
Encapsulation and Constructors
Building Java Programs
Multiple if-else boolean Data
Implementing Classes Chapter 3.
Building Java Programs
CMSC202 Computer Science II for Majors Lecture 07 – Classes and Objects (Continued) Dr. Katherine Gibson Based on slides by Chris Marron at UMBC.
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
CSG2H3 Object Oriented Programming
Presentation transcript:

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

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.

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

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

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

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

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.

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.

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

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 ###-##-####

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

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

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

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

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.

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.

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.

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

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

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

Another Example

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.

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.

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

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

Data and Methods for the Class?

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

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

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.

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

More Special Methods

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

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

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?

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

//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"); }

More on Classes Commenting classes this pointer

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

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.

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

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

this We will cover its use in constructors later.

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.

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.

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

Notes

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

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.

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?

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

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.

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.

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

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.

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.

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