Class Definitions and Writing Methods Chapter 3 3/31/16 & 4/4/16.

Slides:



Advertisements
Similar presentations
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.
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
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors reading:
UML Basics & Access Modifier
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.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
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.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
10-Nov-15 Java Object Oriented Programming What is it?
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.
RECITATION 4. Classes public class Student { } Data Members public class Student { private String name; public String id; }
CSC 142 Computer Science II Zhen Jiang West Chester University
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.
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.
CreatingClasses-SlideShow-part31 Creating Classes part 3 Barb Ericson Georgia Institute of Technology Dec 2009.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 9 Objects and Classes.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 3 A First Look at Classes and Objects.
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.
CIS162AD Constructors Part 2 08_constructors.ppt.
CS 116 Lecture 1 John Korah Contains content provided by George Koutsogiannakis & Matt Bauer.
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 10/12/15 & 10/13/15 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education.
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-3: Constructors; Encapsulation reading: self-checks: #13-18,
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors, Encapsulation, this reading:
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
Review What is an object? What is a class?
Class Definitions and Writing Methods
HKCT Java OOP Unit 02 Object Oriented Programming in Java Unit 02 Methods, Classes, and Objects 1.
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
User-Defined Classes and ADTs
Defining Your Own Classes
Building Java Programs
Encapsulation and Constructors
Building Java Programs
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.
Building Java Programs
ITE “A” GROUP 2 ENCAPSULATION.
CSG2H3 Object Oriented Programming
Presentation transcript:

Class Definitions and Writing Methods Chapter 3 3/31/16 & 4/4/16

Objectives Given a description a class, list its data fields and member methods. Write a class once you have decided what its data fields and member methods are. Describe the use of the access modifiers public and private. Write a member method definition.

Objectives Call a method given its header. Describe the effect of a given call to a method. After writing a class definition, write a driver to test the class.

Objects Have Data Have Methods  Things the object can do. Example – Clock  Data?  Methods?

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

Classes A class defines a new type that can group data and methods to form an object. Sample classes with methods and data associated with them.  e.g. nextDouble( ) is a method of Scanner.  A JFrame has a length and width data.

Designing a Class To design a class, first decide what data the class will have and what methods it will have. Once the class is defined we can make objects of that type. 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 member 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 Write the member methods. Have public access modifier Leave off “static” They can access the data fields Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010

Data Fields Fields: month, day, year a)Declared within a class b)private access modifier Outside classes can't access them. c)Allocated within an object of the class d)Each object, or instance, has its own month, day and year data fields. e)Data fields also called instance variables.

Class Methods Methods – define the class' behaviors.  printUS(), printEU() Some methods to set the data field values:  setMonth, setDay(), setYear()

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

public class SimpleDriver { public static void main(String[] args) { SimpleDate today = new SimpleDate(); today.setMonth(4); today.setDay(4); today.printDateUS(); today.printDateEU(); SimpleDate tomorrow = new SimpleDate(); tomorrow.printDateUS(); }

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 to store the values passed to them. We will use the values to initialize the data fields.

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

Continue Here 4/14/2016 & 4/18/16

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. Add comments to the SimpleDate class.  Next Slide Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010

//Class that represents a date public class SimpleDate { private int month; private int day; private int year; // Gives the month the value passed to the method. public void setMonth(int m){ month = m; } // Gives the day a value public void setDay(int d){ day = d; } //Prints the date in US format public void printDateUS(){ System.out.println(month + "/" + day + "/" + year); } //Prints the date in EU format public void printDateEU(){ System.out.println(day + "/" + month + "/" + year); }

The this pointer Allows an object to reference itself. It can be used when a local variable has the same name as a field has. 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; }

Chapter 9 4/14/2016 & 4/18/2016

Data and Methods for the Class?

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

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

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.

Notes

Constructors-Later 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