Class 9: Static Methods and Data Members

Similar documents
Introduction to Computation and Problem Solving

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Slide 1 CS 170 Java Programming 1

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

Using APIs. Chapter 3. Outline Fields Overall Layout. Java By Abstraction Chapter 3. Field Summary static double PI

CISC-124. This week we continued to look at some aspects of Java and how they relate to building reliable software.

More About Objects and Methods

More About Objects and Methods. Objectives. Outline. Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich.

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

COMP 202 Java in one week

Programming - 2. Common Errors

More About Objects and Methods. Objectives. Outline. Chapter 6

More About Objects and Methods

CS 231 Data Structures and Algorithms, Fall 2016

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

M e t h o d s a n d P a r a m e t e r s

1007 Imperative Programming Part II

More About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario

Options for User Input

Text User Interfaces. Keyboard IO plus

Math Modeling in Java: An S-I Compartment Model

Topics. The Development Process

AP Computer Science Unit 1. Writing Programs Using BlueJ

Chapter 2 Exercise Solutions

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Advanced Computer Programming

More About Objects and Methods

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

Programming with Java

Introduction to Computation and Problem Solving. Class 25: Error Handling in Java. Prof. Steven R. Lerman and Dr. V. Judson Harward.

Practice Midterm 1 Answer Key

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

*Java has included a feature that simplifies the creation of

First Java Program - Output to the Screen

5.6.1 The Special Variable this

ITI Introduction to Computing II

Introduction to Java Applications

Lecture Static Methods and Variables. Static Methods

Software and Programming 1

Lecture Static Methods and Variables. Static Methods

Object Oriented Programming in C#

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

Introduction to Java Unit 1. Using BlueJ to Write Programs

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

1.00 Lecture 2. What s an IDE?

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

CSC Java Programming, Fall Java Data Types and Control Constructs

AP Computer Science Unit 1. Writing Programs Using BlueJ

Practice Midterm 1. Problem Points Score TOTAL 50

index.pdf January 21,

Final Exam CS 152, Computer Programming Fundamentals December 5, 2014

BlueJ Demo. Topic 1: Basic Java. 1. Sequencing. Features of Structured Programming Languages

ICOM 4015 Advanced Programming Laboratory. Chapter 1 Introduction to Eclipse, Java and JUnit

Software and Programming 1

Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part B

Making New instances of Classes

2 Getting Started. Getting Started (v1.8.6) 3/5/2007

APCS Semester #1 Final Exam Practice Problems

Robots. Byron Weber Becker. chapter 6

Java Object Oriented Design. CSC207 Fall 2014

Lab 9: Creating a Reusable Class

Do this by creating on the m: drive (Accessed via start menu link Computer [The m: drive has your login id as name]) the subdirectory CI101.

Classes and Objects Part 1

if (x == 0); System.out.println( x=0 ); if (x = 0) System.out.println( x=0 );

CS112 Lecture: Working with Numbers

ITI Introduction to Computing II

ITI Introduction to Computing II

Lecture Notes for CS 150 Fall 2009; Version 0.5

The Essence of OOP using Java, Nested Top-Level Classes. Preface

Lecture 5: Methods CS2301

Introduction to Computation and Problem Solving

Object oriented programming (OOP): Just an extension to modularity. Why objects? 1. What is an object? Prof. Dionne Aleman.

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

Class 26: Linked Lists

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Programs as Models. Procedural Paradigm. Class Methods. CS256 Computer Science I Kevin Sahr, PhD. Lecture 11: Objects

Lab # 2. For today s lab:

Inf1-OOP. Data Types. Defining Data Types in Java. type value set operations. Overview. Circle Class. Creating Data Types 1.

Object-Based Programming. Programming with Objects

Tutorials. Tutorial every Friday at 11:30 AM in Toldo 204 * discuss the next lab assignment

Chapter 6 Lab Classes and Objects

Java: Classes. An instance of a class is an object based on the class. Creation of an instance from a class is called instantiation.

Programming Languages and Techniques (CIS120)

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

(A) 99 (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

Inheritance and Interfaces

CSCI 161 Introduction to Computer Science

ITI Introduction to Computing II

CS 177 Week 15 Recitation Slides. Review

Use the scantron sheet to enter the answer to questions (pages 1-6)

Java Basics Lecture: January 26, 2012 (On-line Lecture 1)

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

COMP 202 Java in one week

Transcription:

Introduction to Computation and Problem Solving Class 9: Static Methods and Data Members Prof. Steven R. Lerman and Dr. V. Judson Harward Goals This the session in which we explain what static means. You will learn how to write classes with static methods and data members. You will modify a simple class using the BlueJ IDE. 2 1

The UnitCircle Program public class UnitCircle { public static void main( String [] args ) { double circum = 2 * Math.PI; System.out.println( "Circumference of the unit circle = " + circum ); 3 Math.PI double circum = 2 * Math.PI; What is Math? Class, object, or method? How do you know? Can you create Math instances? What is PI? Class, data member, or method? It's defined as public static final double PI = 3.14159265358979323846; final makes it read only 4 2

Why Math.PI is static If PI is a data member, what object does it belong to? We can't create Math instances so it can't belong to an instance of the Math class. Because PI is declared static, it belongs to the Math class object. Access it using the class name, not an object reference. Yes, even classes are objects. How many Math class objects are there in any Java program? How many PI data members? 5 System.out.println() System.out.println( "Circumference= " + circum ); What is System? Class, object or method? Can you create an instance of System? What is out? Class, object, data member, method? What is println()? In what class do you think println() is declared? How do you think System.out is declared? 6 3

System.out public final static PrintStream out; public so that we can print to it from any object final so that the user can't replace it You can not replace a final object reference, but you can modify the object referred to. Every time we call println() we modify out. static so that there will be exactly one output connection to the user's terminal window PrintStream because that class has all the right methods 7 Classes Without Instances (Preview) How do you write a class that can not have instances? Declare it to be abstract public abstract class NoInstanceClass {... 8 4

Classes Without Instances (Preview) Make the default constructor private public class NoInstanceClass { private NoInstanceClass() { If a class has no constructor, Java will supply a default constructor But if you supply any constructor, then Java won't create one. If you define only one constructor and make it private, you can't create an instance outside the class. 9 When Do static Members get Initialized? Just before they are used. In general the compiler takes care of this. But the compiler can't resolve paradox: public class Init { // Evil public static final int i1 = 2*i2; public static final int i2 = 2*i1; 10 5

staticcolors Java has a Color class that we will use extensively when we create graphic user interfaces. The usual way to create a new Color is to use a constructor that takes a red, green and blue component: Color tangerine = new Color( 255, 100, 50 ); Color also defines certain frequently used colors as static so you don t need to create them. For instance, Color.red is defined as 11 public final static Color red = new Color(255, 0, 0); Summary of static Data Members Belong to the class, not an instance of the class so there is only one copy Typically public so you can access them using MyClass.myStatic Often final so they can not be changed Typically uses: Defined constants: Math.PI, Color.red Fixed resources: System.out 12 6

static Methods Normal methods are called on an instance of a particular class. A good example from PS2 is the getvolume() method that you were asked to write as part of the Tank class. It used the tank radius and length given as constructor arguments to calculate and return the tank volume. Tank t = new Tank( 5.0, 20.0 ); System.out.println( t.getvolume() ); static methods are not called on an instance. Instead they are conceptually called on the class. 13 Example Methods Why does the Java entry point method public static void main( String [] args ) have to be static. Why is Math.pow( double a, double b ) static? Why is int Integer.parseInt( String s ) static? Why isn t the int intvalue() method in Integer static? Why isn t System.out.println( String s ) static? 14 7

The Syntax of static Methods Defining: // static public static int parseint( String s ) // instance public int intvalue(); Calling: int ival = Integer.parseInt( "42" ); Integer bigi = new Integer( "42" ); ival = bigi.intvalue(); 15 static Methods Can't Access Instance Data or Methods Find the errors (2): public class StaticError { private int k; public StaticError() { k = 42; public int getvalue() { return k; public static void main( String [] args ) { int k2 = 2*k; System.out.println( "k= " + getvalue() ); 16 8

Instance or static as a Matter of Style Sometimes it is just a matter of style whether you declare a method to be an instance or a static method. Consider a class Work used for physics and engineering calculations. The constructor takes 2 arguments, a double and a String indicating the units of the first argument. Remember that a confusion on this issue between NASA and a contractor led to the loss of a Mars probe a few years ago. 17 class Work public class Work { public static final String JOULE = "joule"; public static final String LBF = "foot-pound"; public static final String BTU = "btu";... private double val; // in joules public Work( double w, String units ) {... 18 9

Instance or static, 2 Which is the better way to add two instances of Work? public static Work add(work w1, Work w2); or public Work add( Work w ); 19 BlueJ Exercise Using your browser, navigate to Lecture9. and download static.zip. Double click static.zip and extract it to a new directory. Start BlueJ and navigate to the directory in which you unpacked the static.zip file. You will see two icons: an orange rectangle labeled Street and a text file icon. Double click the text file icon and proceed from there. 20 10