Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Basics II Minseok Kwon

Similar presentations


Presentation on theme: "Java Basics II Minseok Kwon"— Presentation transcript:

1 Java Basics II Minseok Kwon (jmk@cs.rit.edu)
Department of Computer Science Rochester Institute of Technology

2 Review Questions Which variable names are valid? Output? class X_1 {
public static void main(String args[]) { int aInt; int countUpTo5; int 5IsA_niceNumber; int ooo\"; int notToMany:areAllowd; } Output? class X_2{ public static void main(String args[]) { System.out.println("I like to play " ); System.out.println("I like to play " + 6 * 2 ); System.out.println("I like to play " + ( ) ); }

3 Review Questions Does this compile? Why or why not?
class X_3 { public static void main(String args[]) { i += 64; System.out.println("1. " + ( i << 2 ) ); } Does this compile? Why or why not? class X_4 { public static void main(String args[]) { int i = 0; i += 63; System.out.println("1. " + ( i++ >> 2 ) ); System.out.println("2. " + ( 1 > 2 ? 3 : 6 )); System.out.println("3. " + ( 1 > 2 ? 3 : 4 < 5 ? 6 : 9 < 10 ? 7 : 8)); System.out.println("4. " + (1 > 2 ? 3 : (4 < 5 ? 6 : (9 < 10 ? 7 : 8)))); }

4 Review Questions Output? class X_5 {
public static void main( String args[] ) { int n = 0; while ( true ) { System.out.println("before here"); here: { System.out.println("after here"); if ( n > 4 ) System.exit(0); if ( n++ == 0 ) System.out.println("n == 0"); else if ( n++ == 1 ) { System.out.println("n == 1"); break; } else if ( n++ == 2 ) System.out.println("n == 2"); else break here ; }

5 Result % java X_5 before here after here n == 0

6 Object Oriented Programming
Cookie and Cookie cutter ?

7 What is Object Oriented Programming (OOP)?
OOP gained mainstream acceptance in the 1990’s thanks to languages like C++ and Java. The goal behind OOP is to organize a program in a way which mirrors the real world. The real world is composed of objects which have attributes and activities. A Java program can be viewed as a series of objects which interact with each other.

8 What is an Object? The state defines the current object, and the behavior defines what the object can do. An object encapsulates both its state and behaviors into one entity. Example: a Circle object radius = 5 findArea() findCircumference() OOP the state is the current value/s of the data fields the behavior is the set of supported methods r=5 The real world

9 What is a Class? A class is a blueprint for creating objects of the same type. Example: a Circle class in Java class Circle { double radius = 5.0; double findArea() { return radius * radius * Math.PI; } double findCircumference() { return 2 * Math.PI * radius; Class name Data (state) Methods (behavior)

10 Questions: Objects versus Classes
What is an object and what is a class? Movie...Star Wars Rose...Flower Band...Pink Floyd Acura NSX...Car Programming Language...Java College...UW-Oshkosh Guinness...Beer Movie...Star Wars Rose...Flower Band...Pink Floyd Acura NSX...Car Programming Language...Java College...UW-Oshkosh Guinness...Beer class/object object/class

11 Object Oriented Programming -- Revisited
Cookie and Cookie cutter Cookie is an object Cookie cutter is a class

12 Instantiation An object is an instance of the class.
You can create many instances from the same class. Creating an instance is referred to as instantiation. radius = 5 radius = 5 radius = 5 findArea() findArea() findArea() findCircumference() findCircumference() findCircumference()

13 Instantiation class instantiates objects class Circle {
double radius = 5.0; double findArea() { return radius * radius * Math.PI; } double findCircumference() { return 2 * Math.PI * radius; class instantiates radius = 5 find... objects

14 Creating Objects in Java?
Objects are created using the new operator, followed by the class name. new ClassName(); Example: To create a circle object, new Circle(); radius = 5 find...

15 Object Reference Variables
We must have some way to use an object! A name that refers to an object is a reference variable. To create a reference variable, use the class name followed by the reference variable name. ClassName objectReference; To create a reference to a Circle called myCircle: Circle myCircle; myCircle reference name null reference value reference type Circle

16 Putting It All Together
We can write this in one statement: Circle myCircle = new Circle(); Question: How do we create a Rectangle object using rect as its reference variable name? myCircle Circle address radius = 5 find...

17 Primitives vs. Objects With primitive types, like int, the variable holds the actual value. int myInt = 10; With objects, the reference holds an address which refers to the actual object. Circle myCircle = new Circle(); myInt 10 int myCircle radius = 5 address1 find... Circle

18 Question: Primitives vs. Objects
Draw the memory diagram which represents each declaration statement: double myDouble = 5.5; Generator myGen = new Generator(); Circle myCircle1 = new Circle(); char myChar = ’A’; String str = new String(“Hello”); Circle myCircle2 = new Circle(); String str2 = new String(“Goodbye”);

19 Primitive Assignment When do we use assignments? Primitive assignment:
Copy the value. Primitive assignment: int i = 10; int j; j = i; i j 10 ??? int int i int 10 j value 10 is copied

20 Reference Assignment Reference/object creation: address1 address2
Circle circle1 = new Circle(); Circle circle2 = new Circle(); circle1 radius = 5 address1 find... Circle different values for address circle2 radius = 5 address2 find... Circle

21 Reference Assignment Reference assignment: address1 address1
circle2 = circle1; circle1 radius = 5 address1 find... Circle address in circle1 is copied into circle2 circle2 radius = 5 address1 find... Circle

22 Question: Assignments
Draw the memory diagram which represents each assignment statement: double myDouble = 5.5; Generator myGen = new Generator(); Circle myCircle1 = new Circle(); char myChar = ’A’; String str = new String(“Hello”); Circle myCircle2 = new Circle(); String str2 = new String(“Goodbye”); myDouble = 10; myChar = ’B’; str2 = str; myCircle2 = myCircle1;

23 Accessing an Object’s Data and Methods
How to access the data and methods in an object? To access the object’s instance data: referenceVariable.data For example: Circle circle1 = new Circle(); int radius = circle1.radius; circle1 radius radius = 5 address1 5 find... Circle int

24 Accessing an Object’s Data and Methods
To invoke an object’s instance method: referenceVariable.methodName(arguments); For example: double area = circle1.findArea(); area circle1 radius = 5 address1 find... double Circle

25 Question: Accessing What’s wrong (if anything) with the following code snippets? Circle myCircle; System.out.println(myCircle.findArea()); Circle myCircle = new Circle(); System.out.println(myCircle.radius()); System.out.println(myCircle.findArea); System.out.println(Circle.findArea()); int x; System.out.println(x); new Circle().findArea(); 1. 2. 3. did not create a Circle object findArea is not being called as a method did not create a circle object, so you can’t call findArea() no problem - x is a primitive no problem - this is an example of an anonymous object 4. 5.

26 What’s Next? Now we understand
The difference between objects and classes How to create an object from a given class The difference between primitives and objects (e.g., assignment) How to access object’s data and methods The next question is how we define a class?

27 Constructors If you recall the Circle class that we defined before, how can we initialize its radius? To do this, we need a constructor that is a special kind of method to perform initializing the data fields of objects. A constructor uses the same name as the defining class (no return type, not even void), and is invoked when a new object is created. class Circle { double radius = 5.0; Circle() {} Circle(double newRadius) { radius = newRadius; } double findArea() { return radius * radius * Math.PI; double findCircumference() { return 2 * Math.PI * radius; Circle c1, c2; c1 = new Circle(); c2 = new Circle(1.0);

28 Static Variables As you know, we can create multiple instances (possibly with different states) from one class. What if we want all the instances of a class to share data? Use static variables which store values for the variables in a common memory location. In such a case, all objects of the same class are affected if one object changes the value of a static variable. This variable is also called a class variable. Use the keyword static to declare a static variable.

29 Example: Static Variables
class Circle { private double radius; private static int numOfObjects = 0; public Circle() { radius = 1.0; numOfObjects++; } public Circle(double newRadius) { radius = newRadius; public double findArea() { return radius * radius * Math.PI; public static int getNumOfObjects() { return numOfObjects; Circle c1, c2; c1 = new Circle(); System.out.println(c1.getNumOfObjects()); c2 = new Circle(1.0); System.out.println(Circle.getNumOfObjects()); System.out.println(c2.getNumOfObjects()); c1, c2, Circle all have the same value. class name

30 Static Methods Static methods can be called without creating an instance of the class. class Circle { public static void printCircle(Circle c) { System.out.println(c); } public static void main(String[] args) { Circle myCircle = new Circle(); printCircle(myCircle); Suppose that the class Foo is defined in (a). Let f be an instance of Foo. Which of the statements in (b) are correct? public class Foo { int i; static String s; void imethod() { } static void smethod() { System.out.println(f.i); System.out.println(f.s); f.imethod(); f.smethod(); System.out.println(Foo.i); System.out.println(Foo.s); Foo.imethod(); Foo.smethod();

31 Example: Static Methods
What is wrong with the following code? public class MyClass { private int privateVar = 100; public static void change(int val) { privateVar = val; } public class Test { public static void main(String args[]) { MyClass.change(500); public class StaticTest { public void callMe() { } public static void main(String args[]) { callMe();

32 Visibility What do you think about the code segment below? Good or bad? Circle c = new Circle(); c.radius = 30; This is bad since it breaks data encapsulation. How can we fix this? We will restrict access to data or methods using the keywords. public data or methods are visible to the outside. private data or methods are only visible to the inside. What if we would like to access or modify the value of private data? This will require us to write accesors and mutators.

33 Example: Visibility class Circle { private double radius = 5.0;
// Constructors public double findArea() { return radius * radius * Math.PI; // no error! } public static void main(String args[]) { Circle c = new Circle(); c.radius = 10.0; // error or not? class Circle { private double radius = 5.0; // Constructors public double getRadius() { // accessor return radius; } public void setRadius(double newRadius) { // mutator radius = newRadius; public static void main(String args[]) { Circle c = new Circle(); c.setRadius(10.0); // much better! int r = c.getRadius(); // much better!

34 System.out.println(c);
Parameter Passing We know that when passing a primitive, its value is copied (call by value). What if an object is passed as a parameter? Public class TestPassObject { public static void main(String args[]) { Circle myCircle = new Circle(); printCircle(myCircle); } public static void printCircle(Circle c) { c.setRadius(10.0); System.out.println(c); c myCircle address1 address1 radius = 5 Circle Circle find... System.out.println(c);

35 counter variable Scope
The Scope of Variables A variable’s scope is the region of a program within which the variable can be referred to by its name. public class MyClass { instance/class variable/constant declarations public void aMethod ( method parameters ) { local variable declarations for ( int counter; …) { } Instance/ class variable/ constant Scope Method parmeter Scope Local variable Scope counter variable Scope

36 The Scope of Variables If a local variable has the same name as a class’s variable, the local variable takes precedence. public class Foo { int x = 0; // instance variable int y = 0; Foo() { } void p() { int x = 1; // local variable System.out.println(“x = “ + x); System.out.println(“y = “ + y);

37 One Potential Problem Sometimes you need to reference a class’s hidden variable in a method. public class Foo { private int i = 5; private static double k = 0; void setI(int i) { i = i; } static void setK(double k) { Foo.k = k; Different from static variables (e.g., Foo.k = k), it is ambiguous whether i refers to instance variable i or parameter i in the method setI. How can we make this clear?

38 The this Keyword Use the keyword this!
The keyword this gives a way to refer to the instance variables for the current object. In this case, this is the name of the current object. public class Foo { private int i = 5; private static double k = 0; void setI(int i) { this.i = i; } static void setK(double k) { Foo.k = k; Invoking f1.setI(10) is to execute f1.i = 10, where this is replaced by f1. Invoking f2.setI(45) means?

39 The this Keyword The keyword this is often useful in a constructor.
private double x; // X coordinate of the Point private double y; // Y coordinate of the Point public Point( double x, double y ) { this.x = x; this.y = y; } Or use different names for parameters. private double x; // X coordinate of the Point private double y; // Y coordinate of the Point public Point( double newX, double newY ) { x = newX; y = newY; }

40 The keyword this as a constructor
The keyword this can also be used inside a constructor to invoke another constructor of the same class. public class Circle { private double radius; public Circle(double radius) { this.radius = radius; } public Circle() { this(1.0); public double getArea() { return this.radius * radius * Math.PI;


Download ppt "Java Basics II Minseok Kwon"

Similar presentations


Ads by Google