Chapter 9 - Classes with Class Members Class Variables Class Methods How to Access Class Members When to Use Class Members Class Constants Example Program.

Slides:



Advertisements
Similar presentations
The Line Class Suppose you are involved in the development of a large mathematical application, and this application needs an object to represent a Line.
Advertisements

Chapter 6 - Object-Oriented Programming
CSCI 1100/1202 April 3, Testing A program should be executed multiple times with various input in an attempt to find errors Debugging is the process.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Road Map Introduction to object oriented programming. Classes
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)
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
Encapsulation CMSC 202. Types of Programmers Class programmers – Developers of new classes – Goal: Expose the minimum interface necessary to use a new.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Writing Classes (Chapter 4)
Chapter 7 Object-Oriented Programming – Additional Details Object Creation - a Detailed Analysis Assigning a Reference Testing Objects For Equality Passing.
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.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
C# D1 CSC 298 Elements of C# code (part 2). C# D2 Writing a class (or a struct)  Similarly to Java or C++  Fields: to hold the class data  Methods:
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
ECE122 Feb. 22, Any question on Vehicle sample code?
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Java development environment and Review of Java. Eclipse TM Intergrated Development Environment (IDE) Running Eclipse: Warning: Never check the “Use this.
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.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 8 Objects and Classes Object Oriented programming Instructor: Dr. Essam H. Houssein.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
1 CS 177 Week 11 Recitation Slides Class Design/Custom Classes.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
IT108 Objects and Classes Part I George Mason University Revised 4/3/2012.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Attribute - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 12/24/2016.
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.
Class & Objects C++ offers another user-defined data type known class which is the most important feature of the object-oriented programming. A class can.
Lecture 9: Object and Classes Michael Hsu CSULA. 2 OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object.
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.
Lecture 3: Introduction to Object and Classes Michael Hsu CSULA.
Lecture 3: Introduction to Object and Classes Michael Hsu CSULA.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
ENCAPSULATION. WHY ENCAPSULATE? So far, the objects we have designed have all of their methods and variables visible to any part of the program that has.
Defining Your Own Classes II
Topic: Classes and Objects
Examples of Classes & Objects
Some Eclipse shortcuts
Java Primer 1: Types, Classes and Operators
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
CSC240 Computer Science III
Object Based Programming
Introduction to Computer Programming
Pass by Reference, const, readonly, struct
Classes & Objects: Examples
6 Chapter Functions.
Simple Classes in Java CSCI 392 Classes – Part 1.
Static is one of the modifiers that determine variable and method characteristics. The static modifier associates a variable or method with its class.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Java Programming Language
Chapter 9 - Classes with Class Members
Arrays Arrays are represented by objects but there is no class that array objects are instances of. Variables of array type are declared using bracket.
Corresponds with Chapter 5
Chapter 7 Objects and Classes
Chapter 5 Classes.
Presentation transcript:

Chapter 9 - Classes with Class Members Class Variables Class Methods How to Access Class Members When to Use Class Members Class Constants Example Program Using Class Members 1

Class Variables Based on what you've learned so far, when you're working on an object-oriented program, you should envision separate objects, each with their own set of data and behaviors (instance variables and instance methods, respectively). That's a valid picture, but you should be aware that in addition to data and behaviors that are specific to individual objects, you can also have data and behaviors that relate to an entire class. Since they relate to an entire class, such data and behaviors are referred to as class variables and class methods, respectively. For a particular class, each of the class's objects has its own copy of the class's instance variables. For a particular class, each of the class's objects shares a single copy of the class's class variables. 2

Class Variables If you'd like a variable to be shared throughout its class, make it a class variable by using the static modifier in its declaration: static ; Example: public class Mouse { private static int mouseCount; private static double averageLifeSpan;... Class variables are declared at the top of the class, above all the methods. 3

Class Variables Class variables use the same default values as instance variables: integer types get 0 floating point types get 0.0 boolean types get false reference types get null What are the default values for the class variables in this code fragment? public class Mouse { private static int mouseCount; private static double averageLifeSpan; private static String researcher; private static int simulationDuration = 730;... Initializations are allowed. 4

Scope You can access a class variable from anywhere within its class; i.e., you can access class variables from instance methods as well as from class methods. That contrasts with instance variables, which you can access only from instance methods. Thus, class variables have broader scope than instance variables. Local variables, on the other hand, have narrower scope than instance variables. They can be accessed only within one particular method. 5

Scope Here is the scope continuum: Narrower scope equates to more encapsulation, and encapsulation means you are less vulnerable to inappropriate changes. Class variables, with their broad scope and lack of encapsulation, can be accessed and updated from many different places, and that makes programs hard to understand and debug. Having broader scope is necessary at times, but in general you should try to avoid broader scope. Thus, you should prefer local variables over instance variables and instance variables over class variables. local variablesinstance variablesclass variables narrowest scopebroadest scope 6

Class Methods If you have a method that accesses class variables and not instance variables, then you should declare the method to be a class method. To do so, add static to the method's heading like this: static ( ) Example: public class Mouse { private static int mouseCount; private static double averageLifeSpan; public static void printMouseCount() { System.out.println("Total mice = " + Mouse.mouseCount); } To access a class variable, prefix it with dot. 7

How to Access Class Members Normally, to access a class member (a class variable or a class method), prefix it with dot. Shortcut syntax for a class member: In accessing a class member, you may omit the dot prefix if the class member is in the same class as where you're trying to access it from. For example: public class Mouse { private static int mouseCount; private static void printMouseCount() { System.out.println("Total mice = " + Mouse.mouseCount); } public static void main(String[] args) { Mouse.printMouseCount(); } } // end Mouse class OK to access mouseCount without dot. OK to access printMouseCount without dot. 8

When to Use Class Methods You should make a method a class method: If you have a method that uses class variables and/or calls class methods, then it's a good candidate for being a class method. Warning: If in addition to accessing class members, the method also accesses instance members, then the method must be an instance method, not a class method. If you might need to call a method even when there are no objects from the method's class, then you should make it a class method. The main method has to be a class method. If a main method uses helper methods that don't involve instance members, then the helper methods should be class methods as well. 9

Class Constants Sometimes, you'll want a class variable to be fixed/constant. That type of "variable" is called a class constant. To make a class constant, declare a variable with the static and final modifiers like this: static final = ; Note that class constants should be assigned as part of an initialization statement. If you attempt to assign a value to a class constant later on, that generates a compilation error. As with most variables, class constants usually use the private modifier. However, if the constant is so important that more than one class needs to use it, then you should use the public modifier. 10

Class Constants In the below Human class, we make NORMAL_TEMP a class constant (with the static and final modifiers) because all Human objects have the same normal temperature of 98.6° Fahrenheit. public class Human { private static final double NORMAL_TEMP = 98.6;... public boolean isHealthy() { return Math.abs(currentTemp - NORMAL_TEMP) < 1; } // end isHealthy public void diagnose() { if ((currentTemp - NORMAL_TEMP) > 5) { System.out.println("Go to the emergency room now!");... } // end class Human class constant 11

Class Constants Prior to this chapter, you used named constants that were declared locally within a method. For example: public void calculateSignalDelay(double cableDistance) { final double SPEED_OF_LIGHT = ; double propagationDelay; // time for electron to travel // length of cable... propagationDelay = cableDistance / SPEED_OF_LIGHT;... } So when should you use a local variable named constant and when should you use a class constant? Use a local variable named constant if the constant is only needed within one method. Use a class constant if the constant is a property of the collection of all the objects in the class or of the class in general. 12

Example Program Using Class Members /************************************************************* * PennyJar.java * Dean & Dean * * This class counts pennies for individual penny jars and for * all penny jars combined. *************************************************************/ public class PennyJar { public static final int GOAL = 10000; private static int allPennies = 0; private int pennies = 0; //********************************************************** public int getPennies() { return this.pennies; } //********************************************************** public void addPenny() { System.out.println("Clink!"); this.pennies++; PennyJar.allPennies++; if (PennyJar.allPennies >= PennyJar.GOAL) { System.out.println("Time to spend!"); } } // end addPenny 13

Example Program Using Class Members //********************************************************** public static int getAllPennies() { return PennyJar.allPennies; } } // end class PennyJar /********************************************************* * PennyJarDriver.java * Dean & Dean * * This class drives the PennyJar class. *********************************************************/ public class PennyJarDriver { public static void main(String[] args) { PennyJar pennyJar1 = new PennyJar(); PennyJar pennyJar2 = new PennyJar(); pennyJar1.addPenny(); pennyJar2.addPenny(); System.out.println(pennyJar1.getPennies()); System.out.println(PennyJar.getAllPennies()); } // end main } // end class PennyJarDriver 14