Object - Oriented Programming
Object - Oriented Programming
Lab #3
Contents
• Classes
– class
– object
– method
• The new operator
• The this operator
• Method Overloading
• Constructor
2
Classes and Objects
• Class: A class is a blueprint or prototype from which objects are
created
• Object: An object is an instance of a class. The relationship is such
that many objects can be created using one class. Each object has
its own data but its underlying structure (i.e., the type of data it
stores, its behaviors) are defined by the class. An object has both
data and actions (methods).
object
class bicycle
3
Classes
• A class is a collection of fields (data) and methods (procedure or
function) that operate on that data
Instance of the
Circle circle class
center
radius
circumference() x,y
area()
4
Classes (Contd)
• The basic syntax for a class definition:
class ClassName
{
[fields declarations]
[methods declarations]
}
5
Adding Fields: Class Circle with fields
• Add fields
Instance Variables
public class Circle {
public double x, y; //centre coordinate
public double r; // radius of the circle
}
Instance Variables Type
Modifiers: Specifies the
visibility of the instance
variable.
6
Adding Methods
• A class with only data fields has no life. Objects created by such a
class cannot respond to any messages.
7
Adding Methods (Contd)
• Method definition have the following parts
– Modifier
– Return type
– Method name
– List of parameters Method signature
– Method body
8
Adding Methods to Class Circle
9
Classes - Example
• Note: You need to create 2 classes in the project, one with name
DateFirstTry and one with name DateFirstTryDemo which is the
main class
10
The new Operator
• The new Operator
– The new operator is used to create an object of a class and associate the
object with a variable that names it
• Syntax
– Class variable = new Class();
• Example
– DateFirstTry date1 = new DateFirstTry();
11
Creating objects of a class
Date date1 = new Date(4, 1776);
Date date2 = new Date(16, 1789);
date1 = date2;
12
Instance Variable and Methods
• In order to use an object we can reference its instance variables
or methods using dot(.) notation
• objectIdentifier.variableIdentifier
• objectIdentifier.methodName
13
The return keyword
• The return keyword immediately stops execution of a method
– Jumps back to whatever called that method
– Returns a value
14
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
– default: accessible in classes in the same package and the class itself
15
A few notes on visibilities
• You can NOT specify visibilities for method variables
– Any method variable can only be accessed within that method
16
Variables
• There are several kinds of variables:
– Member variables in a class – these are called fields or
instance variables
17
Classes – Example2
Output:
November 9, 1990
May 23, 1995
18
Self-Test (1)
• 프로젝트 명: Project03_1
– git commit –m “Project03_1”
• DateFirstTry를 수정할 것
– instance variable
• String type의 month 변수
• int type의 day 변수
– makeItNewYears 메소드
• instance variable month를 “January”로, day를 1로 바꾸는 메소드
(year는 바뀌지 않는다)
• 매개변수를 가지지 않음, return type은 void
– yellIfNewYear 메소드
• instance variable month가 “January”이고 day가 1일 경우 “Happy New Year!”를,
그렇지 않을 경우 “Not New Year’s Day.”를 출력하는 메소드
• 매개변수를 가지지 않음, return type은 String
19
Self-Test (1)
• DateFirstTryDemo를 수정할 것
– DateFirstTry 클래스의 date1 객체 생성
• month와 day는 오늘 날짜로 설정`
– DateFirstTry 클래스의 date2 객체 생성
• month와 day는 각자의 생일로 설정
• 생일이 1월 1일 일 경우 다른 날짜로 설정
– date2 객체를 통해 makeItNewYears 메소드 호출
• 수행 결과
20
The this Reference
• In Java, the this reference is used to refer to the object you are
inside of at this moment
21
The this Reference (Contd)
I am this
object.
My name is
alice and I am
23.
test1
name: alice
age: 23
22
Concepts
• Information Hiding is the practice of separating how to use a
class from the details of its implementation
– Abstraction is another term used to express the concept of discarding
detail in order to avoid information overload
23
Accessor-Mutator methods
• An accessor method (getter) is used to return the value of a
private field
• It follows a naming scheme prefixing the word “get” to the start
of the method name
24
Classes – Example2 (Contd)
25
Method Overloading
• Methods must all have different headers
• Methods within a class can have the same name if they have
different parameter lists
• Differentiated by the number and the type of the arguments
passed into the method
26
Overloading Example
27
Overloading Example (Contd)
28
Constructor
• A constructor is a special member function whose name is always
the same as the name of the class
• The constructor cannot have any return type – not even void
29
Classes - Example3
Overloaded constructors
30
equals()
• It is expected by java that objects be able to determine if they are equal to
another.
– The equals() method returns a Boolean
– True if the object is the same. False if it is not.
– The programmer must determine the criteria for objects being equal.
anotherPer
son
name: Fred
age: 25
31
toString()
• It is useful for an object to return a string representation of itself.
– The toString() method returns this String.
– The programmer must determine the information that is returned by the method.
Person
name: Fred
age: 25
32
Method notes
• You can put the methods in a class in any order
– Java doesn’t care which one is listed first
– Thus, you can call a method listed later within another method
• All methods must specify a return type
– If it’s void, then no value is returned
33
Class Outline
34
Class Outline (Contd)
instance variables
constructors
setter (mutator)
toString()
other methods
equals()
35
Automatic garbage collection
• The object which does not have a reference and cannot be used
in future
date1 date2
The Q has no reference variable
so it will be collected by the
P Q Garbage Collector.
36
Self-Test (2)
• 프로젝트 명: Project03_2
– git commit –m “Project03_2”
– 당일 밤 12시까지 제출
37
Self-Test (2)
• Employee 클래스를 생성할 것
– employee의 String name, int age, String position, int salary,
int vacationDays 를 저장하기 위한 private variable을 만들 것
– 3개의 생성자를 만들 것
• name, age만 설정하는 생성자
• name, age, position, salary를 설정하는 생성자
• 모든 instance variable을 설정하는 생성자
• 만약 position이 설정되지 않을 경우 default는 “Engineer”로 설정됨
• 만약 salary가 설정되지 않을 경우 default는 15000로 설정됨
• 만약 vacationDays가 설정되지 않을 경우 default는 20으로 설정됨
– instance variable salary를 변경하는 set public method를 만들 것
– employee에 대한 정보를 출력하는 outInfo() public method를 만들 것
– int type 값을 매개변수로 받는 vacation() public method를 만들 것
• employee가 휴가를 신청할 때 사용하는 메소드
• 인자보다 vacationDays가 크거나 같을 경우 vacationDays가 인자만큼 차감되고 “Possible”을
return함
• 인자보다 vacationDays가 부족할 경우 vacationDays는 차감되지 않고 “Impossible”을
return함
– Employee 객체를 인자로 전달받아 호출한 객체와 name과 age, Position가 같은 지 여부를 출력
하는 equals() public method를 만들 것
38
Self-Test (2) (Contd)
• EmployeeManager를 생성할 것
– 다음과 같은 객체를 생성할 것
• employee1: Name: Walter White, Age: 42, Position: Manager, Salary: 20000
• emplyoee2: Name: Jesse Pinkman, Age: 32, Position: Assistant Manager, Salary: 12000,
vacationDays: 7
• employee3: Name: Jimmie McGill, Age: 38
• employee4: Name: Chuck McGill, Age : 40
• employee5: Name: Walter White, Age: 42, Position: Manager, Salary: 20000
– Walter White 의 Salary를 21000으로 변경할 것
– Walter White 와 Jesse Pinkman 의 정보를 출력할 것
– Jimmie가 휴가를 10일 신청할 경우를 출력할 것
– Jesse Pinkman 가 휴가를 10일 신청할 경우를 출력할 것
– Jimmie의 정보를 출력할 것
– employee1과 employee2의 name과 age, Position가 같은 지 출력할 것
– employee1과 employee5의 name과 age, Position가 같은 지 출력할 것
39
Self-Test (2) (Contd)
40