Download as pdf or txt
Download as pdf or txt
You are on page 1of 61

Object-Oriented Programming

Lab #4, #5
Contents
• Static In Java
• Math Class
• Wrapper Classes
• Variables and Memory
• Class Parameters
• new
• null
• privacy leaks
• copy constructor
• deep copy vs. shallow copy

2
Static
• A class can have data and methods of its own (not part of the objects)

• For example, Employeeclass can keep a count of the number of objects it has
created

class Employee{
public static int empCount; //not an instance variable

Employee(String name, int age, int salary){
this.name = name;
this.age = age;
this.salary = salary;
empCount++; //increment the number of employees
}
}

3
Static (Contd)
• In Java
public class EmployeeManager {
public static void main (String[] args){
Employee emp1 = new Employee("James Wright", 42, 20000);

Employee emp2 = new Employee("Amy Smith", 27, 15);


Employee emp3 = new Employee("Peter Coolidge", 32, 7);
Employee emp4 = new Employee("John Doe", 22, 10);

System.out.println(emp1.toString()+emp2.toString()+emp3.toString()+emp4.toString());
System.out.println("Number of Employees: "+Employee.empCount +"\n");
}
}

• Employee.empCount is asking Employee class for the count of the


employees created
– Since empCount belongs to class and not the object
– Hence use the class name (Employee) and not object name (emp1,2,3,4) to access
variable empCount

4
Static (Contd)
• Output after running the program.

5
Static (Contd)
• In Java it is possible to declare the following as static
– Variables
• e.g. static int empCount;
– Methods
• e.g. public static double area(double radius){
//calculates the area given the radius
}
– Classes
• Usually used with static inner classes.
• More on this in chap 13
– Static Blocks
• e.g.

static {
...
}

6
Static Variables
• A static variable is a variable that belongs to the class as a whole,
and not just to one object
– There is only one copy of a static variable per class, unlike instance
variables where each object has its own copy

• All objects of the class can read and change a static variable
• Although a static method cannot access an instance variable, a
static method can access a static variable
• A static variable is declared like an instance variable, with the
addition of the modifier static
– private static int myStaticVaraible;

7
Static Variables (Contd)
• Static variable should be defined as private
– private static int empCount;
• unless you are defining a constant.
– public static final double PI = 3.14159;

8
Static Methods
• A static method is one that can be used without a calling object
• A static method still belongs to a class, and its definition is given
inside the class definition
• When a static method is defined, the keyword static is placed in
the method header
– public static returnedType myMethod(parameters) { ... }
• Static methods are invoked using the class name in place of a
calling object
– returnedValue = MyClass.myMethod(arguments);

9
Static Methods (Contd)

10
Main
• The Main method is a well known static method

• You can put a main in any class

• Although the main method is often by itself in a class separate


from the other classes of a program, it can also be contained
within a regular class definition
– In this way the class in which it is contained can be used to create
objects in other classes, or it can be run as a program
– A main method so included in a regular class definition is especially
useful when it contains diagnostic code for the class

11
String args[]
• Parameter in the main method

• Command-line arguments in Java

• When an application is launched, the runtime system passes the


command-line arguments to the application’s main method via an
array of Strings.

12
String args[]
• From the menu bar select Run -> Run Configuration

13
The Math Class
• The Math class is an important built-in class
• Contains static variables and methods.
• Collection of common math functions (sin, cos, sqrt, etc.)
• Two constants: PI and E

14
The Math Class (Contd)
• The Math class provides a number of standard mathematical
methods
– It is found in the java.lang package, so it does not require an import
statement
– All of its methods an data are static, therefore they are invoked with the
class name Math instead of a calling object
– The Math class has two predefined constants, E(𝑒, the base of the natural
logarithm system) and PI(𝜋, 3.14159 ...)
• area = Math.PI * radius * radius;

15
Structure of the Math Class

public class Math {


public static final double PI = 3.141592653589793;

public static double sin(double d) { ... }


public static double sqrt(double d) { ... }

private Math() {}
...
}

16
What’s different about Math Class
• It’s different from a typical Java class
– It is a “stateless” class
– We only need one Math class (not multiple instances)
– No need to instantiate it (hence, no public constructor)
– All of its variables and methods are static
– static means “applies to the class as a whole” vs. “applies to an individual
instance”

17
Some Methods in the class Math
(Part 1 of 5)

18
Some Methods in the class Math
(Part 2 of 5)

19
Some Methods in the class Math
(Part 3 of 5)

20
Some Methods in the class Math
(Part 4 of 5)

21
Some Methods in the class Math
(Part 5 of 5)

22
Random Numbers
• The Math class also provides a facility to generate
pseudo-random numbers
public static double random()
– A pseudo-random number appears random but is really generated by a
deterministic function
• There is also a more flexible class named Random
• Sample use: double num = Math.random();
• Returns a pseudo-random number greater than or equal to 0.0
and less than 1.0

23
Random Numbers
• Example

24
Self-Test
• 프로젝트 명: Project04_1
– git commit –m “Project04_1”

• int a = 60984, int b = 808 일 때, Math 클래스의 2가지 메소드를 호


출하여 두 숫자 중 더 큰 숫자와, 더 작은 숫자를 출력할 것
• double x = 2.0, double y = 3.0일 때, Math 클래스의 메소드를 호출
하여 x^y (x의 y승)과 y^x (y의 x승)을 출력할 것
• 0 에서 10 사이의 난수를 가지는 double type 변수 r을 선언한 후, r을
반지름으로 가지는 원의 면적을 출력할 것
– 𝜋 는 Math 클래스의 변수를 사용할 것
– 𝑟 2 연산은 Math 클래스의 메소드를 사용할 것

25
Self-Test

26
Primitives & Wrapper Classes
• Java’s primitive data types (boolean, int, etc.) are not classes.

• Wrapper classes are used in situations where objects are required.

27
Primitives & Wrapper Classes (Contd)

• Java has a wrapper class for each of the eight primitive data
types:

Primitive Wrapper Primitive Wrapper


Type Class Type Class
boolean Boolean float Float
byte Byte int Integer
char Character long Long
double Double short Short

28
Boxing & Unboxing
• Boxing is the process of wrapping a primitive in its wrapper class
object.
• Simply use the constructor and pass the primitive as a parameter
– Integer integerObj = new Integer(42);
– Double doubleObj = new Double(3.2);
– Boolean boolObj = new Boolean(true);

• Automatic boxing is possible


– Integer integerObj = 42;
– Double doubleObj = 3.2;
– Boolean boolObj = true;

29
Boxing & Unboxing (Contd)
• Unboxing is the process of unwrapping a primitive form its
wrapper class object
• Simply use the <typename>Value() method
– int i = integerObj.intValue();
– double d = doubleObj.doubleValue();
– boolean b = boolean booleanObj.booleanValue();

• Automatic Unboxing is possible


– int i = integerObj;
– double d = doubleObj;
– boolean b = booleanObj;

30
Strings & Wrappers
• The Wrapper class for each primitive type has a method
parseType() to parse a string representation & return the literal
value.

– Integer.parseInt(“42”) => 42
– Boolean.parseBoolean(“true”) => true
– Double.parseDouble(“2.71”) =>2.71

• Common use: Parsing the arguments to a program

31
Strings & Wrappers
• Wrapper classes also have static methods that 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”

32
Example

33
Wrapper class
• NOTE: The operator == checks
equality of memory address, it
should not be used to compare
2 objects.

• You should use the equals() to


compare 2 objects

34
Wrapper class (Contd)
• For each number of Wrapper has a MAX_VALUE constant:

35
Wrapper class (Contd)
• Many useful utility methods, e.g. for Integer:

36
Wrapper class (Contd)
• Double & Float: Utilities for arithmetic operations

– Constants: POSITIVE_INFINITY & NEGATIVE_INFINITY

– Constants: NaN = Not a Number value

– Methods is NaN(), isInfinite()

37
Variables and Memory
• Main memory is used to store data in contiguous bytes.
• The address of the first byte is the address of the data item.

38
Variables and Memory
• Primitive types store the actual value at the memory location
0 20
1
• int i = 20; 2
• char c = ‘h’; 3
• short sh = 10; 4 h
5
6 10
7
8
9
10

39
References
• The memory address to a class variable is its reference
• References are treated differently since the object is not directly
stored here
• References store the memory address where the object is actually
stored

40
References (Contd)

41
References (Contd)

42
Class Parameters
• Call-by-Value
– Java uses the call-by-value mechanism for parameters of primitive-type
– The actual parameter (or argument expression) is fully evaluated and the
resulting value is copied into a location being used to hold the formal
parameter’s value during method execution
– That location is typically a chunk of memory on the runtime stack for the
application

43
Class Parameters (Contd)

• The values of A and B


have not been changed!!!

44
Class Parameters (Contd)
• In case the parameter is of a class type, the value plugged in is a
reference (memory address).
• Any change made to the parameter is made to the object named
by the parameter, because they are the same object. Thus, a
method can change the instance variables of an object given as a
parameter.

45
Class Parameters (Contd)

• In short: A method cannot


change the value of a
parameter of a primitive type.
But a method can change the
value of an object

46
Classes: Review
• Static methods
– Can be used without a calling object
• Static variables
– One copy of a static variable per class
• The Math class
– Provides many standard mathematical methods
• Wrapper classes
– Class types corresponding to primitive types
• Passing Parameters
– A method cannot change the value of a parameter of a primitive type.
But a method can change the value of an object

47
null
• null is a special constant that may be assigned to a variable of
any class type
YourClass yourObject = null;
$null$

• null is not an object: It is, rather, a kind of “placeholder” for a


reference that does not name any memory location
– Because it is like a memory address, use == or != (instead of equals) to
test if a class variable contains null
– if (yourObject == null)

48
new
• The new operator invokes a constructor which initializes an object,
and returns a reference to the location in memory of the object
created
– This reference can be assigned to a variable of the object’s class type

• An object whose reference is not assigned to a variable is called


an anonymous object

49
Maintaining Class privacy
• For a primitive type instance variable, just adding the private
modifier to its declaration should insure that there will be no
privacy leaks
• For a class type instance variable, however, adding the private
modifier alone is not sufficient

• Why is this dangerous?

50
Maintaining Class privacy
• Uses the copy constructor to return a reference. If the copy is
changed, that ahs no effect of the date whose reference is in the
instance variable born.
• A privacy leak can also arise from an incorrectly defined
constructor/mutator method

51
Copy Constructors
• A copy constructor is a constructor with a single argument of the
same type as the class

• The copy constructor should create object that is a separate,


independent object, but with the instance variables set so that it
is an exact copy of the argument object

52
Copy Constructor for a class with
Primitive Type Instance Variables

public Date (Date aDate)


{
if (aDate == null) // Not a real date
{
System.out.println(“Fatal Error. “);
System.exit(0);
}

month = aDate.month;
day = aDate.day;
year = aDate.year;
}

53
Copy Constructor (Contd)

• Notice the difference between


person 3 and 4

54
Deep Copy vs. Shallow Copy
• A deep copy of an object is a copy that, with one exception, has
no references in common with the original
– Exception: References to immutable objects are allowed to be shared

• Any copy that is not a deep copy is called a shallow copy


– This type of copy can cause dangerous privacy leaks in program

55
Deep Copy vs. Shallow Copy (Contd)

56
Deep Copy vs. Shallow Copy (Contd)

57
Mutable vs. Immutable Classes
• When creating classes we create accessors and mutators to allow
us to manipulate private instance variables.

• Classes such as this are said to be mutable


– i.e. It is possible to change the values of instance variables after
construction.

• Having Mutators in classes may break the rules for avoiding


privacy leaks

58
Mutable vs. Immutable Classes (Contd)

• A class that contains no methods (other than constructors) that


change any of the data in object of the class is called an
immutable class
– Objects of such a class are called immutable objects
– It is perfectly safe to return a reference to an immutable object because
the object cannot be changed in any way
– The String, Math class is an immutable class

59
Self-Test (2)
• 프로젝트 명: Project04_2
– git commit –m “Project04_2”
– 당일 밤 12시까지 제출

• 현재 코드에서는 person3의 정보를 수정하면 person2의 정보도 동일하게 수


정된다.
• person3와 person2를 분리시키기 위해 Shallow Copy를 Deep Copy로 변경할

– Copy Constructor를 작성할 것
– person3 객체를 Copy Constructor를 통해 생성하는 것으로 수정할 것

• 현재 코드에서는 person1 객체를 통하지 않고도 person1의 출생일을 변경할


수 있는 Privacy Leak이 발생한다.
• Person 클래스의 Privacy Leak을 없앨 것
– Person 클래스의 출생일을 반환하는 mutator method를 수정할 것

60
Self-Test (2)
• shallow copy를 deep copy로 변경하여 person3를 수정해도 person2
가 수정되지 않도록 변경
• Person 클래스의 mutator method를 수정하여 다른 객체에서
person1의 출생일을 수정할 수 없도록 변경

수정 전 수정 후

61

You might also like