Classes CS 21a: Introduction to Computing I First Semester, 2013-2014.

Slides:



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

Chapter 2: Using Objects Part 1. To learn about variables To understand the concepts of classes and objects To be able to call methods To learn about.
IMPLEMENTING CLASSES Chapter 3. Black Box  Something that magically does its thing!  You know what it does but not how.  You really don’t care how.
 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Introduction to Object-Oriented Programming CS 21a: Introduction to Computing I First Semester,
Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.
1 Classes Object-oriented programming: Model the problem as a collection of objects that have certain attributes and interact with one another and/or the.
Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
Chapter 2 – An Introduction to Objects and Classes Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
CHAPTER 2 OBJECTS AND CLASSES Goals: To understand the concepts of classes and objects To realize the difference between objects and object references.
Datalogi A 2: 15/9. Java Slides based on Horstmann chapter 2&3 Objects and classes Import, methods, references Implementing a class.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William Loftus.
Chapter 3 Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To understand.
About the Presentations The presentations cover the objectives found in the opening of each chapter. All chapter objectives are listed in the beginning.
Understanding class definitions Looking inside classes.
Java Programming Review (Part I) Enterprise Systems Programming.
3.1 Documentation & Java Language Elements Purpose of documentation Assist the programmer with developing the program Assist other programers who.
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Introduction to Objective-C and Xcode (Part 2) FA 175 Intro to Mobile App Development.
Comments are for people Header comments supply basic information about the artifact.
Chapter 1: A First Program Using C#. Programming Computer program – A set of instructions that tells a computer what to do – Also called software Software.
Introduction to Object-Oriented Programming
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.
Week 4 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Introduction to Java and Object-Oriented Programming AJSS Computer Camp Department of Information Systems and Computer Science Ateneo de Manila University.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
The Java Programming Language
Intro and Review Welcome to Java. Introduction Java application programming Use tools from the JDK to compile and run programs. Videos at
Chapter 3 Implementing Classes. Assignment Read 3.1 – 3.5 and take notes complete Self Check Exercises 1-10; Due September 24 th Read 3.6 – 3.8 and take.
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.
Types CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University (Chapter 4, Horstmann text)
Week 4 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Introduction to Java Java Translation Program Structure
1 Principles of Computer Science I Prof. Nadeem Abdul Hamid CSC 120 – Fall 2005 Lecture Unit 2 - Using Objects.
Chapter 4 Introduction to Classes, Objects, Methods and strings
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Class Relationships and Object Interaction CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila.
Anatomy of a Java Program. AnotherQuote.java 1 /** A basic java program 2 * 3 Nancy Harris, James Madison University 4 V1 6/2010.
Using Objects. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L7: Objects Slide 2 Java.
Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
CSH Intro. to Java. The Big Ideas in Computer Science Beyond programming Solving tough problems Creating extensible solutions Teams of “Computational.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
Chapter 3 Implementing Classes
More Sophisticated Behavior
Lecture 3 John Woodward.
Chapter 3 – Implementing Classes
Yanal Alahmad Java Workshop Yanal Alahmad
Chapter 3: Using Methods, Classes, and Objects
Chapter Goals To become familiar with the process of implementing classes To be able to implement and test simple methods To understand the purpose and.
Chapter Three - Implementing Classes
Java Programming with BlueJ
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 1: Computer Systems
JAVA CLASSES.
Defining Classes and Methods
AN INTRODUCTION TO OBJECTS AND CLASSES
Classes CS 21a: Introduction to Computing I
Introduction to Object-Oriented Programming
Defining Classes and Methods
Chap 2. Identifiers, Keywords, and Types
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
Introduction to Computer Science and Object-Oriented Programming
Presentation transcript:

Classes CS 21a: Introduction to Computing I First Semester,

Creating Classes in Java ► Recall: programming in Java means writing classes for objects ► Creating a Java class involves specifying an object’s ► state: instance fields (data private to the object) ► behavior: methods (the public interface of the class)

Instance Fields ► An instance field is a variable ► A variable is a storage location that holds a value ► A variable declaration indicates the variable’s name (e.g., balance) and type (e.g., double) ► Note that each object of a class holds a separate copy of an instance field ► e.g., different bank accounts have different balances (equivalently, different values for the balance field)

Instance Field Examples ► For bank account objects: public class BankAccount { private double balance; … } ► For car objects: public class Car { private int distanceTravelled; private double gasLeft; … } Instance field declaration syntax: ;

Names (identifiers) in Java ► An identifier is a name in a Java program ► used for classes, variables, methods,... ► Rules in forming an identifier: ► consists of letters and digits, $, _ ► should start with a letter or underscore ► canNOT contain spaces ► Examples: balance Ateneo score5 total_credit bigBlue _one4Three x public ► Some identifiers are reserved words

Java Conventions ► Class names ► Start with a capital letter, capitalize first letters of succeeding words ► Examples: BankAccount, Car, HelloAgain ► Variable and method names ► Start with a lowercase letter, capitalize first letters of succeeding words ► aka "camelCase" ► Examples: balance, distanceTravelled, gasLeft ► Following these conventions make your programs easier to read!

Types in Java ► Most common primitive types in Java: ► int: whole numbers, including values like 123, , and 0 ► double: floating point numbers, including values like 5.25, , , and ► Another common type used for instance fields: String ► A "built-in" Java class ► Represents a string of characters, for values like: ″yellow″, ″John Santos″, and ″x-y-z″

Methods ► A method describes a specific behavior applicable to objects of a class ► A method defines a sequence of instructions (or statements) to be carried out when that method is called ► A method is called or invoked on an object of the class ► In the BlueJ environment, this is done by right clicking on an object icon ► In a tester program, this is carried out through the dot operator ( e.g., b.deposit( ); )

Method Composition ► Has a signature and a body ► The method’s signature is written as: ► Syntax: ( ) ► Example: public void deposit( double amount ) ► The method body ► Statements or instructions inside the curly braces (block of code)

Method Declaration Examples public class BankAccount { … public void deposit( double amount ) { double newBalance = balance + amount; balance = newBalance; } … public double getBalance() { return balance; } … }

Method Declaration Examples public class BankAccount { … public void deposit( double amount ) { double newBalance = balance + amount; balance = newBalance; } … public double getBalance() { return balance; } … } method signatures

Method Declaration Examples public class BankAccount { … public void deposit( double amount ) { double newBalance = balance + amount; balance = newBalance; } … public double getBalance() { return balance; } … } statements

Mutator Methods versus Accessor Methods ► Two possible method intents: modify the object’s state or return some information about the object ► A mutator method primarily modifies an objects state ► Usually indicates a void return type (no value returned) ► Usually has parameters ► Instance fields are updated within the method ► Example: public void deposit( double amount ) ► An accessor method returns something about an object ► Usually indicates a return type (some value will be returned); if not, the values are displayed through System.out.println() ► Usually has no parameters ► Example: public double getBalance()

Variables Revisited Three "categories" of variables in a Java class ► Instance fields: belongs to an object ► Example: balance ► Local variables: belongs to a method; holds "temporary" computations ► Example: newBalance ► Parameter variables: belongs to a method; value initialized to the value specified during the method call ► Example: amount

Variable Lifetime ► Instance fields last as long as the objects are in memory ► The variables are created when the object is created and destroyed when the object is destroyed ► Local variables and parameter variables exist only as long as the method they belong to is executing ► The variables are created when method execution begins but are destroyed when execution completes

Variable Lifetime Demo ► Demonstrates: ► that instance fields are part of an object ► when local variables and parameter variables are created and destroyed during a method call ► Acknowledgment: The next slides were taken from Horstmann’s textbook slides

Instance Fields

harrysChecking.deposit(500); Lifetime of Variables – Calling Method deposit

harrysChecking.deposit(500); Lifetime of Variables – Calling Method deposit

harrysChecking.deposit(500); double newBalance = balance + amount; Lifetime of Variables – Calling Method deposit

harrysChecking.deposit(500); double newBalance = balance + amount; balance = newBalance; Lifetime of Variables – Calling Method deposit

Constructor ► A constructor is a special kind of method invoked during object creation ► Its name must match the class name and it has no return type ► Called with the new command, not with. operator; e.g., b = new BankAccount(); ► Multiple constructors may be defined in a single class as long as they have different signatures ► Constructors may have parameters used during initialization

Constructor Examples For the BankAccount class: public class BankAccount { private double balance; public BankAccount() { balance = 0; } public BankAccount( double initialBalance ) { balance = initialBalance; } … }

Some Tips on Implementing a Java Class ► First, decide on the methods names and signatures for the class ► The public interface of the class ► Have empty methods bodies first ► Then, determine the instance fields you need to implement these methods ► Next, implement the methods ► Specify the statements within the methods; the statements will (most likely) access the instance fields ► Finally, test the class ► Write a tester program that creates objects and invokes the methods ► In BlueJ, this may be done interactively

Comments ► The programs you write will likely be read by someone else ► By your instructor or grader ► By other members of a programming team ► Placing comments in your Java classes improves readability and increases professionalism in your code ► Comment syntax: ► Line comments: // comment ► Block comments: /* comment */ ► Note that comments are ignored by the Java compiler ► However, javadoc treats special comment conventions differently

Comment Conventions and javadoc ► The most useful comments are ► Class header comments: describes the class ► Method header comments: describes method uses and other details ► Instance fields: describes role or use of an instance field ► There are existing conventions for writing these comments ► Use block comments and begin with /** instead of /* ► @return) in header comments ► The javadoc program automatically produces a class documentation page (in html) from these comments ► In BlueJ, select Tools->Project Documentation (Ctrl-J)

Order of Declarations ► Declaration of methods, constructors, and instance fields in a class may come in any order ► Most common order used by Java programmers ► Declare instance fields first, then the constructors, finally the methods ► We will use this convention in the programs we demonstrate in this course ► Alternative order: instance fields declared last ► Emphasizes the public interface ► (recommended by the Horstmann textbook)

Testing a Java Class In a separate Java application (inside the main method) ► Create object(s) of the class ► BankAccount john = new BankAccount( ); ► Invoke methods on the object ► john.deposit( ); ► Print values returned by accessor methods to verify the object’s state ► System.out.println( john.getBalance() );

Statements ► The body of a method contains a sequence of statements ► Statements we have used so far: ► Assignments: (some assignments come with declarations) balance = 0; double newBalance = balance + amount; BankAccount b = new BankAccount(); ► Return statements: return balance; // found inside an accessor method ► Method calls: b.withdraw( ); ► Output statements: System.out.println( "Hello, world" ); // this is also a method call ► In general, statements end with a semi-colon

Summary ► A Java class defines instance fields, methods, and constructors ► Instance fields represent an object’s state ► Methods comprise the public interface of the class to be used by another program ► Each method defines a sequence of statements that may affect the object’s state/instance fields ► Methods may include local variables and parameters ► Constructors are special methods that initialize the instance fields of an object