Visibilities and Static-ness

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

Static Methods Static methods are those methods that are not called on objects. In other words, they don’t have an implicit parameter. Random number generation.
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.
Access to Names Namespaces, Scopes, Access privileges.
Enhancing classes Visibility modifiers and encapsulation revisited
CS 106 Introduction to Computer Science I 03 / 30 / 2007 Instructor: Michael Eckmann.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
28-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
1 Review for Midterm 3 CS 101 Spring Topic Coverage  Loops Chapter 4  Methods Chapter 5  Classes Chapter 6, Designing and creating classes.
Options for User Input Options for getting information from the user –Write event-driven code Con: requires a significant amount of new code to set-up.
Methods and You. Up to this point, I have covered many different data types with you. Variables can be considered the nouns of an English sentence. If.
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.
Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To.
Parameters. Overview A Reminder Why Parameters are Needed How Parameters Work Value Parameters Reference Parameters Out Parameters.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
Introduction to Computation and Problem Solving Class 9: Static Methods and Data Members Prof. Steven R. Lerman and Dr. V. Judson Harward.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
CSC 142 Computer Science II Zhen Jiang West Chester University
Session 7 Methods Strings Constructors this Inheritance.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
MIT AITI 2004 – Lecture 13 Abstract Classes and Interfaces.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
Programming for Geographical Information Analysis: Core Skills Lecture 4: Program Flow II Methods.
1 Classes Chapter 4 Spring 2005 CS 101 Aaron Bloomfield.
More on Objects Mehdi Einali Advanced Programming in Java 1.
Peyman Dodangeh Sharif University of Technology Spring 2014.
Classes, Interfaces and Packages
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Attribute - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 12/24/2016.
Structured Programming Dr. Atif Alhejali Lecture 4 Modifiers Parameters passing 1Structured Programming.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
External Scope CECS 277 Mimi Opkins.
Inheritance.
Topic: Classes and Objects
Classes and Objects Introduced
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
Chapter 4 Spring 2006 CS 101 Aaron Bloomfield
Inheritance ITI1121 Nour El Kadri.
Overriding Method.
Chapter 11 Inheritance and Polymorphism
Classes & Objects.
Lecture 4 D&D Chapter 5 Methods including scope and overloading Date.
Namespaces, Scopes, Access privileges
Advanced Programming in Java
CS 302 Week 11 Jim Williams, PhD.
Advanced Programming in Java
CSC240 Computer Science III
Chapter 9 Inheritance and Polymorphism
Lecture 11 C Parameters Richard Gesick.
OOP Paradigms There are four main aspects of Object-Orientated Programming Inheritance Polymorphism Abstraction Encapsulation We’ve seen Encapsulation.
Outline Writing Classes Copyright © 2012 Pearson Education, Inc.
Review for Midterm 3.
Review for Midterm 3.
Namespaces, Scopes, Access privileges
Tonga Institute of Higher Education
Basics of OOP A class is the blueprint of an object.
Fall 2018 CISC124 2/24/2019 CISC124 Quiz 1 marking is complete. Quiz average was about 40/60 or 67%. TAs are still grading assn 1. Assn 2 due this Friday,
Method of Classes Chapter 7, page 155 Lecture /4/6.
CMPE212 – Reminders Assignment 2 due next Friday.
Chapter 11 Inheritance and Encapsulation and Polymorphism
Review for Midterm 3.
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Object-Oriented Design AND CLASS PROPERTIES
Presentation transcript:

Visibilities and Static-ness Aaron Bloomfield CS 101-E

field is not initialized Our Circle class We are going to write a Circle class Somebody else is going to use it public class Circle { double radius; double Pi = 3.1415926536; } Note the radius field is not initialized Remember that a variable of a class is called a field Note the fields are not static We’re ignoring the public for now

Using our Circle class public class CircleTest { Note it’s a different class public class CircleTest { public static void main (String[] args) { int x = 5; Circle c = new Circle(); } public class CircleTest { public static void main (String[] args) { int x = 5; Circle c = new Circle(); } Remember that a variable of a method is just called a variable c is the object Circle is the class Note the new

Accessing our Circle object Any field or method in an object can be accessed by using a period Example: System.in Example: c.radius = 10; Example: c.Pi = 4; This is bad – Pi should have been declared final (this will be done later)

What’s the output? public class Circle { double radius; double Pi = 3.1415926536; } public class CircleTest { public static void main (String[] args) { int x; Circle c = new Circle(); System.out.println (x); Java will give a “variable not initialized” error

What’s the output now? public class Circle { double radius; double Pi = 3.1415926536; } public class CircleTest { public static void main (String[] args) { int x; Circle c = new Circle(); System.out.println (c.radius); Java outputs 0.0!

What’s going on? A (method) variable needs to be initialized before it is used A field (class variable) is automatically initialized by Java All doubles are initialized to 0.0, ints to 0, etc. This is a bit counter-intuitive…

What happens in memory Consider: Circle c = new Circle() A double takes up 8 bytes in memory Thus, a Circle object takes up 16 bytes of memory As it contains two doubles radius = 0.0 Pi = 3.1415926536 Circle c

Consider the following code public class CircleTest { public static void main (String[] args) { Circle c1 = new Circle(); Circle c2 = new Circle(); Circle c3 = new Circle(); Circle c4 = new Circle(); }

What happens in memory There are 4 Circle objects in memory Taking up a total of 4*16 = 64 bytes of memory radius = 0.0 Pi = 3.1415926536 Circle c1 radius = 0.0 Pi = 3.1415926536 Circle c2 radius = 0.0 Pi = 3.1415926536 Circle c3 radius = 0.0 Pi = 3.1415926536 Circle c4

Consider the following code public class CircleTest { public static void main (String[] args) { Circle c1 = new Circle(); //... Circle c1000000 = new Circle(); } This program creates 1 million Circle objects!

… What happens in memory There are 1 million Circle objects in memory Taking up a total of 1,000,000*16 = 16 Mb of memory radius = 0.0 Pi = 3.1415926536 Circle c1 radius = 0.0 Pi = 3.1415926536 Circle c2 radius = 0.0 Pi = 3.1415926536 Circle c1000000 … Note that the final Pi field is repeated 1 million times

The use of static for fields If a field is static, then there is only ONE of that field for ALL the objects Total memory usage: 8 Mb + 8 bytes (1,000,000+1=1,000,001 doubles) Total memory usage: 16 bytes (1+1=2 doubles) Total memory usage: 40 bytes (4+1=5 doubles) radius = 0.0 Pi = 3.1415926536 Circle c1 Circle c2 Circle c1000000 … radius = 0.0 Pi = 3.1415926536 Circle c1 Circle c2 Circle c3 Circle c4 radius = 0.0 Pi = 3.1415926536 Circle c

More on static fields What does the following print Note that Pi is not final Circle c1 = new Circle(); Circle c2 = new Circle(); Circle c3 = new Circle(); Circle c4 = new Circle(); c1.Pi = 4.3; System.out.println (c2.Pi); Note you can refer to static fields by object.field

Even more on static fields There is only one copy of a static field no matter how many objects are declared in memory Even if there are zero objects declared! The one field is “common” to all the objects Thus, you can refer to a static field by using the class name: Circle.Pi

Even even more on static fields This program also prints 4.3: Circle c1 = new Circle(); Circle c2 = new Circle(); Circle c3 = new Circle(); Circle c4 = new Circle(); Circle.Pi = 4.3; System.out.println (c2.Pi);

Even even even more on static fields We’ve seen static fields used with their class names: System.in (type: InputStream) System.out (type: OutputStream) Math.PI (type: double) Integer.MAX_VALUE (type: int) Non-static fields are generally not called dynamic fields Just “non-static”, or no qualifier at all

A bit of humor…

Back to our Circle class public class Circle { double radius; final static double Pi = 3.1415926536; } But it doesn’t do much! Note that Pi is now final and static

Adding a method public class Circle { double radius; final static double Pi = 3.1415926536; double computeArea () { return Pi*radius*radius; } Note that a (non-static) method can use all the fields

Using that method public class CircleTest { public static void main (String[] args) { Circle c = new Circle(); c.radius = 2.0; System.out.println (c.computeArea()); } Prints 12.566370614356

Adding another method double oneOverRadius() { return 1.0/radius; } I couldn’t think of a good reason to divide something by the radius…

What happens now? Code in class CircleTest’s main() method Circle c = new Circle(); // c.radius = 0.0 System.out.println (c.oneOverRadius()); Java won’t crash, but many other programming languages (C and C++, especially) will Java prints “Infinity” Not what we wanted, though!

One way to fix this… public class Circle { double radius = 1.0; Note that the radius field is now initialized to 1.0 public class Circle { double radius = 1.0; final static double Pi = 3.1415926536; double computeArea () { return Pi*radius*radius; } double oneOverRadius() { return 1.0/radius;

Back to our program… This code will now run properly: Circle c = new Circle(); // c.radius = 1.0 System.out.println (c.oneOverRadius()); But this code will “crash”: c.radius = 0.0;

Where the “crash” occurs public class CircleTest { public static void main (String[] args) { Circle c = new Circle(); // c.radius = 1.0 c.radius = 0.0; System.out.println (c.oneOverRadius()); } public class Circle { double radius = 1.0; final static double Pi = 3.1415926536; double computeArea () { return Pi*radius*radius; } double oneOverRadius() { return 1.0/radius; Here is the badly written code Here is where the “crash” occurs

Motivation for private fields Problem: We do not want people using our Circle class to be able to modify the fields on their own Solution: Don’t allow other code to modify the radius field Give it private visibility private means that only code within the class can modify the field

One way to fix this… public class Circle { Note that the radius field is now private public class Circle { private double radius = 1.0; final static double Pi = 3.1415926536; double computeArea () { return Pi*radius*radius; } double oneOverRadius() { return 1.0/radius;

Back to our program… This code will now not compile: Circle c = new Circle(); // c.radius = 1.0 c.radius = 0.0; System.out.println (c.oneOverRadius()); Java will give a compile-time error: radius has private access in Circle

Back to our program… This code will also not compile: Circle c = new Circle(); // c.radius = 1.0 System.out.println (c.radius); Java will give the same compile-time error: radius has private access in Circle

The problem now… But now you can’t have a Circle with a radius other than 1.0! Solution: Use a get/set methods in Circle: void setRadius (double r) { radius = r; } double getRadius () { return radius;

Our Circle class so far public class Circle { double radius = 1.0; final static double Pi = 3.1415926536; double computeArea () { return Pi*radius*radius; } double oneOverRadius() { return 1.0/radius; void setRadius (double r) { radius = r; double getRadius () { return radius;

Using the get/set methods public class CircleTest { public static void main (String[] args) { Circle c = new Circle(); c.setRadius (1.0); System.out.println (c.computeArea()); (c.getRadius()); } public class Circle { private double radius = 1.0; final static double Pi = 3.1415926536; double computeArea () { return Pi*radius*radius; } double oneOverRadius() { return 1.0/radius; void setRadius (double r) { radius = r; double getRadius () { return radius; Here a method is invoked Here the change to radius occurs

Wait! Another problem! Here is the problem now… public class CircleTest { public static void main (String[] args) { Circle c = new Circle(); c.setRadius (0.0); System.out.println (c.oneOverRadius()); } Here is the problem now…

This problem is easily fixed Change the setRadius method to the following void setRadius (double r) { if ( r > 0.0 ) radius = r; } Now there is no way for code outside the Circle class to change the radius to zero

Visibilities in Java There are four visibilities: private: Only code within the same class can access the field or method Note: “access” means reading or writing the field, or invoking the method public: Any code, anywhere, can access the field or method protected: Used with inheritance We won’t get to that this semester package: Almost the same as public This is the default Note that it can’t be specified like the others

A few notes on visibilities You can NOT specify visibilities for method variables Any method variable can only be accessed within that method Think of it as public within the method (after it’s defined) and private outside the method You can also specify visibilities for methods and classes More on that later in the course (or next course)

Constructors When you create a object, you often have to do some initialization You have to “construct” the object public class Circle { String name; public Circle() { Scanner scanner = new Scanner(System.in); System.out.println (“Enter the Circle’s name:”); name = scanner.next(); } //... Note the different method declaration

Constructors, take 2 Now when a Circle is created: Circle c = new Circle(); Java will ask for the Circle’s name, and put it in the name field Okay, so this isn’t the greatest example…

Note that the constructor Constructors, take 3 More useful constructors for our Circle class: public Circle() { radius = 1.0; } public Circle (double r) { radius = r; Note there is no return type for constructors Note that the constructor name is the EXACT same as the class name Note that there are two “methods” with the same name!

Overriding methods (and constructors) Consider the following code: Circle c1 = new Circle (); Circle c2 = new Circle (2.0); Java knows which constructor to call by the list of parameters This is called “overloading” Creates a Circle of radius 1.0 Creates a Circle of radius 2.0

Overriding methods (and constructors), take 2 The following Circle constructors would not be allowed: We are assuming Pi is not final for this example public Circle() { radius = 1.0; } public Circle (double r) { radius = r; public Circle (double p) { Pi = p; When Circle(1.0) is called, which one is meant?

Constructors, take 4 Our second constructor has a problem: public Circle (double r) { radius = r; } Consider the following code: Circle c = new Circle (0.0); System.out.println (c.oneOverRadius()); The method is dividing 1 by zero (again)

Constructors, take 5 Our revised constructors: public Circle() { radius = 1.0; } public Circle (double r) { if ( r <= 0.0 ) else radius = r;

A bit of humor…

Back to the static discussion Remember that there is one (and only one) static Pi field, regardless of how many objects are declared Consider the following method: double getPi() { return Pi; }

The getPi() method It doesn’t read or modify the “state” of any object In this example, it doesn’t read/write the radius In fact, that particular method doesn’t care anything about the objects declared It’s only accessing a static field

Make getPi() static Consider the following: static double getPi() { return Pi; } As the method is static, it can ONLY access static fields A static method does not care about the “state” of an object Examples: Math.sin(), Math.tan(), Math.cos() They don’t care about the state of the Math class They only perform the computation

Invoking static methods As with static fields, they can be called using either an object or the class name: Circle c = new Circle(); System.out.println (c.getPi()); System.out.println (Circle.getPi());

static methods and non-static fields Consider the following (illegal) Circle method: static double getRadius() { return radius; } And the code to invoke it: public static void main (String[] args) { Circle c1 = new Circle(); Circle c2 = new Circle(); Circle c3 = new Circle(); Circle c4 = new Circle(); System.out.println (Circle.getRadius());

What happening in memory There are no Circle objects in memory There are 4 Circle objects in memory Which radius field does Circle.getRadius() want? There are 1 million Circle objects in memory radius = 0.0 Pi = 3.1415926536 Circle c1 Circle c2 Circle c1000000 … radius = 0.0 Pi = 3.1415926536 Circle c1 Circle c2 Circle c3 Circle c4 Pi = 3.1415926536

The main static lesson A static method cannot access or modify the state of the object

static and non-static rules Non-static fields and methods can ONLY be accessed by the object name Static fields and methods can be accessed by Either the class name or the object name Non-static methods can refer to BOTH static and non-static fields Static methods can ONLY access static fields

Back to our main() method public static void main (String[] args) The method does not return a value Any code anywhere can call this method It’s a static method: Can’t access non-static fields Can be called only by the class name

A bit of humor…