Static Members and Methods

Slides:



Advertisements
Similar presentations
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Advertisements

Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Lecture 2: Object Oriented Programming I
Chapter 5 Defining Classes II Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
CS102--Object Oriented Programming
CS102--Object Oriented Programming Lecture 3: – Defining classes (10 questions) – The StringTokenizer class – The Math class Copyright © 2008 Xiaoyan Li.
Static Class Members Wrapper Classes Autoboxing Unboxing.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Chapter 11 Abstract Classes and Interfaces 1. Abstract method New modifier for class and method: abstract An abstract method has no body Compare: abstract.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Java Programming, Second Edition Chapter Four Advanced Object Concepts.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
1 Java Console I/O Introduction. 2 Java I/O You may have noticed that all the I/O that we have done has been output The reasons –Java I/O is based on.
Lecture # 8 Constructors Overloading. Topics We will discuss the following main topics: – Static Class Members – Overloaded Methods – Overloaded Constructors.
 2005 Pearson Education, Inc. All rights reserved Methods: A Deeper Look.
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
Slides prepared by Rose Williams, Binghamton University Chapter 5 Defining Classes II.
Chapter 4 -2 part Writing Classes 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
Java Classes Chapter 1. 2 Chapter Contents Objects and Classes Using Methods in a Java Class References and Aliases Arguments and Parameters Defining.
Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
 Definition: Accessing child class methods through a parent object  Example: Child class overrides default parent class methods  Example: Child class.
CSC 142 Computer Science II Zhen Jiang West Chester University
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo CET 3640 © Copyright by Pearson Education, Inc. All Rights Reserved.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Abstract Classes and Interfaces Chapter 9 CSCI 1302.
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.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Java Classes Chapter 1. 2 Chapter Contents Objects and Classes Using Methods in a Java Class References and Aliases Arguments and Parameters Defining.
COMP 110 Static variables and methods Luv Kohli October 29, 2008 MWF 2-2:50 pm Sitterson 014.
Chapter 5 Defining Classes II Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Attribute - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 12/24/2016.
1 Lecture # 2. * Introducing Programming with an Example * Identifiers, Variables, and Constants * Primitive Data Types * Byte, short, int, long, float,
Slides prepared by Rose Williams, Binghamton University Chapter 5 Defining Classes II.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Chapter 5 Defining Classes II
INTERMEDIATE PROGRAMMING USING JAVA
3 Introduction to Classes and Objects.
Java Primer 1: Types, Classes and Operators
Chapter 5 Defining Classes II
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.
Static and non-Static Chapter 5.
CMSC 202 Static Methods.
CSC240 Computer Science III
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 3 Introduction to Classes, Objects Methods and Strings
Classes and Objects Miscellany: Statics, Wrappers & Packages
5 Variables, Data Types.
Chapter 6 Methods: A Deeper Look
Wrapper Classes The java.lang package contains wrapper classes that correspond to each primitive type: Primitive Type Wrapper Class byte Byte short Short.
Chapter 5 Defining Classes II
Classes and Objects 5th Lecture
Java Classes and Objects 3rd Lecture
More About Objects and Methods
Chapter 5 Defining Classes II
Chapter 5 Defining Classes II
Classes and Objects Static Methods
Object Oriented Programming in java
Classes, Objects and Methods
Outline Creating Objects The String Class The Random and Math Classes
Chapter 4 Constructors Section 4.4
Classes and Objects Object Creation
CMSC 202 Constructors Version 9/10.
Presentation transcript:

Static Members and Methods CMSC 202

What Does “static” Mean? Instance variables, constants, and methods may all be labeled as static. In this context, static means that the variable, constant, or method belongs to the class. It is not necessary to instantiate an object to access a static variable, constant or method. 2

Static Constants A static constant may either be public or private. The value of a static defined constant cannot be altered. Therefore it is safe to make it public. Making it public allows client programmers to use it. A private constant can only be used within the class definition. The declaration for a static defined constant must include the modifier final, which indicates that its value cannot be changed. public static final int INVENTED = 1769; public static final String INVENTOR = "Nicolas-Joseph Cugnot"; Static constants belong to the class as a whole, not to each object, so there is only one copy of a static constant. It is available to the client programmer (if it’s public) and to all objects of the class. When referring to such a defined constant outside its class, use the name of its class in place of a calling object. int year = Car.INVENTED; String inventor = Car.INVENTOR; 3

Static Variables A static variable belongs to the class as a whole, not just to one object. There is only one copy of a static variable per class. All the member functions of the class can read and change a static variable. A static variable is declared with the addition of the modifier static. private static int myStaticVariable; Static variables can be declared and initialized at the same time. private static int myStaticVariable = 0; 4

Static Variables vs. Instance Variables Instance variables are local to the instance in which they are created. Notice the results of a mutator modifying the value contained. private static int numWheels = 4; public int getNumWheels(){ return numWheels; } public void setNumWheels(int nWheels){ numWheels = nWheels; public static void main(String args[]){ Car defaultCar = new Car(); Car chevy = new Car("9431a",2000,"Chevy","Cavalier"); Car dodge = new Car("8888","Orange","Dodge","Viper", 5,400,2,1996); System.out.printf("NumWheels: chevy %d dodge %d default %d%n", chevy.getNumWheels(), dodge.getNumWheels(), defaultCar.getNumWheels()); dodge.setNumWheels(-2); chevy.setNumWheels(5); static variables can be changed!!! NumWheels: chevy 4 dodge 4 default 4 NumWheels: chevy -2 dodge -2 default -2 NumWheels: chevy 5 dodge 5 default 5

call the static function. Static Methods So far, class methods required a calling object in order to be invoked. These are sometimes known as non-static methods. Static methods: Still belong to a class, but need no calling object, and often provide some sort of utility function. Static methods are called on the class name (as opposed to an instance name) Car myCaddy = new Car("82978",2011,"Cadillac","Escalade"); System.out.println("My Caddy "+ ((myCaddy.hasSpoiler())? "a spoiler" : "no spoiler")); public static Car[] findAntiques(Car[] cars) { /* ... */ } Car[] antiques = Car.findAntiques(cars); for(Car c: antiques) { System.out.println(c); } Use the class name to call the static function. 6

Rules for Static Methods Static methods have no calling/host object (they have no this). Therefore, static methods cannot: Refer to any instance variables of the class Invoke any method that has an implicit or explicit this for a calling object Static methods may invoke other static methods or refer to static variables and constants. A class definition may contain both static methods and non-static methods. 7

Static Temperature Converting Examples public class Temperature { public static double convertFahrenheitToCelsius(double degreesF){ return 5.0/9.0 * (degreesF - 32); } public static double convertFahrenheitToKelvin(double degreesF){ return (degreesF + 459.67) * (5.0/9.0); public static void main(String[] args){ double degreesF = 100; // since we have 2 static methods, no instances // of the TemperatureConverter class are required System.out.printf("%f degrees Fahrenheit%n", degreesF); System.out.printf(" is %f Celsius%n", Temperature.convertFahrenheitToCelsius(degreesF)); System.out.printf("is %f Kelvin%n", Temperature.convertFahrentoKelvin(degreesF)); 8

public static void main(String [] args) main is a Static Method Let us take note that the method signature of main( ) is public static void main(String [] args) Being static has two effects: main can be executed without an object. “Helper” methods called by main must also be static. 9

Any Class Can Have a main( ) Every class can have a public static method name main( ). Java will execute main in whichever class is specified on the command line. java <className> A convenient way to write test code for your class. 10

Static Review public class C Given the skeleton class definition below public class C { public int a = 0; public static int b = 1; public void f( ) {…} public static void g( ) {…} } Can body of f( ) refer to a? Can body of f( ) refer to b? Can body of g( ) refer to a? Can body of g( ) refer to b? Can f( ) call g( )? Can g( ) call f( )? For each, explain why or why not. 11

The Math Class (Static Class) The Math class provides a number of standard mathematical methods. All of its methods and data are static. They are invoked with the class name Math instead of a calling object. The Math class has two predefined constants, E (e, the base of the natural logarithm system) and PI (π, 3.1415 . . .). area = Math.PI * radius * radius; 12

Copyright © 2008 Pearson Addison-Wesley. Wrapper Classes Wrapper classes Provide a class type corresponding to each of the primitive types Makes it possible to have class types that behave somewhat like primitive types The wrapper classes for the primitive types: byte, short, int, long, float, double, and char are (in order) Byte, Short, Integer, Long, Float, Double, and Character Wrapper classes also contain useful predefined constants static methods Copyright © 2008 Pearson Addison-Wesley. All rights reserved 13

The Boolean class has names for two constants of type Boolean. Constants and Static Methods in Wrapper Classes Wrapper classes include constants that provide the largest and smallest values for any of the primitive number types. Integer.MAX_VALUE, Integer.MIN_VALUE, Double.MAX_VALUE, Double.MIN_VALUE, etc. The Boolean class has names for two constants of type Boolean. Boolean.TRUE corresponds to true Boolean.FALSE corresponds to false of the primitive type boolean. Copyright © 2008 Pearson Addison-Wesley. All rights reserved 14

Constants and Static Methods in Wrapper Classes Some static methods convert a correctly formed string representation of a number to the number of a given type. The methods Integer.parseInt(), Long.parseLong(), Float.parseFloat(), and Double.parseDouble() do this for the primitive types (in order) int, long, float, and double. Static methods convert from a numeric value to a string representation of the value. For example, the expression Double.toString(123.99); returns the string value "123.99" The Character class contains a number of static methods that are useful for string processing. Copyright © 2008 Pearson Addison-Wesley. All rights reserved 15

public static void main (String[ ] args) Wrappers and Command Line Arguments Command line arguments are passed to main via its parameter conventionally named args. public static void main (String[ ] args) For example, if we execute our program as java proj1.Car Shelby Cobra 1967 then args[0] = “Shelby”, args[1] = “Cobra”, and args[2] = “1967”. We can use the static method Integer.parseInt( ) to change the argument “1967” to an integer variable via Each Wrapper Class has the ability to parse its primitive type from a string int year = Integer.parseInt(args[2]); 16

Copyright © 2008 Pearson Addison-Wesley. Boxing Boxing: The process of converting from a value of a primitive type to an object of its wrapper class. Create an object of the corresponding wrapper class using the primitive value as an argument The new object will contain an instance variable that stores a copy of the primitive value. Unlike most other classes, a wrapper class does not have a no-argument constructor. The value inside a Wrapper class is immutable. Integer integerObject = new Integer(5); Copyright © 2008 Pearson Addison-Wesley. All rights reserved 17

Copyright © 2008 Pearson Addison-Wesley. Unboxing Unboxing: The process of converting from an object of a wrapper class to the corresponding value of a primitive type. The methods for converting an object from the wrapper classes Byte, Short, Integer, Long, Float, Double, and Character to their corresponding primitive type are (in order) byteValue, shortValue, intValue, longValue, floatValue, doubleValue, and charValue. None of these methods take an argument. int i = integerObject.intValue(); Copyright © 2008 Pearson Addison-Wesley. All rights reserved 18

Automatic Boxing and Unboxing Starting with version 5.0, Java can automatically do boxing and unboxing for you. Boxing: rather than: Unboxing: Integer integerObject = 5; Integer integerObject = new Integer(5); int i = integerObject; int i = integerObject.intValue(); Copyright © 2008 Pearson Addison-Wesley. All rights reserved 19