MIT AITI 2004 Lecture 10 Static and Final. public class MyMath { public double PI = 3.14159; public double square (double x) { return x * x; } public.

Slides:



Advertisements
Similar presentations
The Point Class public class Point { public double x; public double y; public Point(double x0, double y0) { x = x0; y = y0; } public double distance(Point.
Advertisements

Topic 10 Java Memory Management. 1-2 Memory Allocation in Java When a program is being executed, separate areas of memory are allocated for each class.
Constructors & An Introduction to Methods. Defining Constructor – Car Example Public class car { String Model; double speed; String colour; { Public Car.
Objects and Classes Writing Your Own Classes A review.
Dialogs. Displaying Text in a Dialog Box Windows and dialog boxes –Up to this our output has been to the screen –Many Java applications use these to display.
Classes with multiple methods Part 1. Review of classes & objects Early on, we learned that objects are the basic working units in object-oriented programs.
Like our natural language. Designed to facilitate the expression and communication ideas between people and computer Like our natural language. Designed.
Saravanan.G.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,
Dale Roberts Procedural Programming using Java Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and.
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.
Lecture # 5 Methods and Classes. What is a Method 2 A method is a set of code which is referred to by name and can be called (invoked) at any point in.
Copyright © Curt Hill Mathematics Functions An example of static methods.
CSC Programming I Lecture 5 August 30, 2002.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 4 part 3 GEORGE KOUTSOGIANNAKIS.
Lecture # 8 Constructors Overloading. Topics We will discuss the following main topics: – Static Class Members – Overloaded Methods – Overloaded Constructors.
Mt. Rushmore, South Dakota CSE 114 – Computer Science I Static Methods andVariables.
SE-1010 Dr. Mark L. Hornick 1 Some Java Classes using & calling methodsS.
 2005 Pearson Education, Inc. All rights reserved. 1 Methods Called functions or procedures in other languages Modularize programs by separating its tasks.
Java Program Components Java Keywords - Java has special keywords that have meaning in Java. - You have already seen a fair amount of keywords. Examples.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Slides prepared by Rose Williams, Binghamton University Chapter 5 Defining Classes II.
Java Classes Chapter 1. 2 Chapter Contents Objects and Classes Using Methods in a Java Class References and Aliases Arguments and Parameters Defining.
10-Nov-15 Java Object Oriented Programming What is it?
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Java - Classes JPatterson. What is a class? public class _Alpha { public static void main(String [] args) { } You have been using classes all year – you.
Chapter 9: A Second Look at Classes and Objects
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
Classes. Student class We are tasked with creating a class for objects that store data about students. We first want to consider what is needed for the.
MIT AITI 2004 – Lecture 13 Abstract Classes and Interfaces.
1 Basic Java Constructs and Data Types – Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C.
Lecture 10:Static & Final Kenya © 2005 MIT-Africa Internet Technology Initiative MyMath Example public class MyMath { public double PI = ;
Chapter 3 Introduction to Classes and Objects Definitions Examples.
Methods. Methods also known as functions or procedures. Methods are a way of capturing a sequence of computational steps into a reusable unit. Methods.
Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.
Sahar Mosleh California State University San MarcosPage 1 The Class String There is no primitive type for strings in Java The class String is a predefined.
AP Computer Science A – Healdsburg High School 1 static Keyword in Java - Static variables - Static methods.
The Math class Java provides certain math functions for us. The Math class contains methods and constants that can be very useful. The Math class is like.
The Math Class Methods Utilizing the Important Math Operations of Java!
Chapter 5 Defining Classes II Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Method OverloadingtMyn1 Method overloading Methods of the same name can be declared in the same class, as long as they have different sets of parameters.
1 Class and Object Lecture 7. 2 Classes Classes are constructs that define objects of the same type. A Java class uses instance variables to define data.
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.
Structured Programming Dr. Atif Alhejali Lecture 4 Modifiers Parameters passing 1Structured Programming.
Jeopardy $100 VariablesErrorsLoops Classes and Objects Program Structure $200 $300 $400 $500 $400 $300 $200 $100 $500 $400 $300 $200 $100 $500 $400 $300.
Lecture 6: Methods MIT-AITI Kenya © 2005 MIT-Africa Internet Technology Initiative In this lecture, you will learn… What a method is Why we use.
For Friday Read No quiz Program 6 due. Program 6 Any questions?
(C) 2010 Pearson Education, Inc. All rights reserved.  Best way to develop and maintain a large program is to construct it from small, simple pieces,
CSC 205 Programming II Lecture 4 Abstract Class. The abstract keyword indicate that a class is not instantiable Defining a type which will be specialized.
Basic Class Structure. Class vs. Object class - a template for building an object –defines the instance data that the object will hold –defines instance.
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
CPSC 233 Tutorial 12 March 4/5 th, TopHat Quiz int[] a = {0}; int[] b = {1}; a = b; What is the value of a[0] i) 0 ii) 1.
Topic: Classes and Objects
Java Memory Management
Java Memory Management
“Form Ever Follows Function” Louis Henri Sullivan
Static Members and Methods
More About Objects and Methods
Lecture 4 Using Classes Richard Gesick.
Static and non-Static Chapter 5.
Chapter 6 Methods: A Deeper Look
CS2011 Introduction to Programming I Methods (II)
Take out a piece of paper and PEN.
METHODS, CLASSES, AND OBJECTS A FIRST LOOK
Chapter 2: Java Fundamentals cont’d
Methods/Functions.
Chapter 11 Inheritance and Encapsulation and Polymorphism
Presentation transcript:

MIT AITI 2004 Lecture 10 Static and Final

public class MyMath { public double PI = ; public double square (double x) { return x * x; } public static void main(String[ ] args) { MyMath m = new MyMath(); System.out.println("m: value of PI is " + m.PI); System.out.println("m: square of 5 is " + m.square(5)); MyMath n = new MyMath(); System.out.println("n: value of PI is " + n.PI); System.out.println("n: square of 5 is " + n.square(5)); } MyMath Example

In Example 1, to calculate the square of 5 we need to create an instance of MyMath class: MyMath m = new MyMath(); Then we invoke it’s square() method with the argument 5: m.square(5); Objects Review

MyMath Output The results of invoking square() method on instances m and n are the same: m: value of PI is m: square of 5 is 25 n: value of PI is n: square of 5 is 25 square() behaves the same no matter which instance it is called on. So... why not have one square() method for the entire class?

Also... The value of PI = is the same for all instances of MyMath class. Why do we need to store a value of PI separately for each instance of MyMath ? Instead, can we have only one common value of PI for the whole MyMath class?

MyMath with static public class MyMath { // add keyword "static" to field declaration public static double PI = ; // add keyword "static" to method declaration public static double square (double x) { return x * x; } // main method is always declared "static" public static void main( String[ ] args) { // MyMath m = new MyMath(); - No longer need this line! // MyMath n = new MyMath(); - No longer need this line! // Now invoke square() method on the MyMath class System.out.println("Value of PI is " + MyMath.PI); System.out.println("Square of 5 is" + MyMath.square(5)); }

Static Pi Field We added word static to the declaration of the final variable PI : public static double PI = ; It means that now we have only one value of variable PI for all instances of MyMath class; PI is now a class data field

The final keyword We declared PI as public static double PI = ; but this does not prevent changing its value: MyMath.PI = ; Use keyword final to denote a constant : public static final double PI = ; Once we declare a variable to be final, it's value can no longer be changed!

Final References Consider this final reference to a Point : public static final Point ORIGIN = new Point(0,0); This prevents changing the reference ORIGIN : MyMath.ORIGIN = new Point(3, 4); BUT! You can still call methods on ORIGIN that change the state of ORIGIN. MyMath.ORIGIN.setX(4);

MyMath with static & final public class MyMath { // add keyword final to field declaration public static final double PI = ; public static double square (double x) { return x * x; } public static void main( String[ ] args) { System.out.println("Value of PI is " + MyMath.PI); System.out.println("Square of 5: " + MyMath.square(5)); }

Static Fields Only one instance of a static field data for the entire class, not one per object. "static" is a historic keyword from C/C++ "Class fields" is a better term –As opposed to "instance fields"

Static Square Method We also added the word "static" to the declaration of the method square() : public static double square(double x) { return x * x; } Now the method square() is shared by all instances of the class—only one square method for the class, not one for each instance.

Static Methods Static methods do not operate on a specific instance of their class Have access only to static fields and methods of the class –Cannot access non-static ones "Class methods" is a better term –As opposed to "instance methods"

Let's take a look at Java's Math class in the API You cannot create an instance of the Math Class, it's just a place to store useful static methods All the methods and fields are static: Math.sqrt(16) Math.PI Math.abs(-3) Java's Math Class

Static Field Examples Constants used by a class (usually used with final keyword) –Have one per class; don’t need one in each object public static final double TEMP_CONVERT= 1.8; –If this is in class Temperature, it is invoked by –double t = Temperature.TEMP_CONVERT * temp; –Constants are all capital letters by tradition (C, C++) –For example: PI, TEMP_CONVERT etc.

Static Method Examples For methods that use only the arguments and therefore do not operate on an instance public static double pow(double b, double p) // Math class, takes b to the p power For methods that only need static data fields Main method in the class that starts the program –No objects exist yet for it to operate on!

POP QUIZ Should it be static or non-static? Speed of light field getName() method in a Person class A sum method that returns the resulting of adding both its arguments Width data field in a Rectangle class static non static non