Title: Describing the world (1)
1Describing the world (1)
- Describe a particular person
- Ayse has long blond hair, green eyes, is 1.63m
tall, weighs 56Kg and studies computer
engineering. Now lying down asleep. - Mehmet studies electronics, has short black hair
and brown eyes. He is 180cm and 75 kilos. Now
running to class! - Notice how all have specific values of
- name, height, weight, eye color, state,
2Describing the world (2)
- Type/category determine an objects properties
functionality - Person
- has name, height, weight, can run, sleep,
- Category gives default properties
- Ayse is a person with green eyes. We
infer/assume she has two of them, as well as two
legs, arms, nose, mouth, hair, can speak, run,
sleep, etc! - Can concentrate on relevant properties
3Java OOP terminology
- Class - Category
- Properties/states
- Functionality/Services(examines/alters state)
data
methods
- object - Individual/unique thing (an instance
of a class) - Particular value for each property/state
- functionality of all members of class.
4Java OOP Software
- Software System
- Set of objects
- Which interact with each other
Created (instantiated) from class definitions
Person
One object will send a message to another object
asking it to do a particular task. The first
object does not need to know how the task is done
(only how to request that it be done.) This
corresponds to calling one of the second
objects methods!
David
David Say your name
5In more detail
- Create manipulate person objects
6Coding Java Classes
// header public class Person //
properties // constructors // methods
7Coding Java Classes
public String getName() return name
public String getComments() return comments
public void setComments( String someText)
comments someText
get set methods for some properties(no
setName!)
public void increaseAge() age age 1
public double getNetSalary() double
netSalary netSalary salary - TAX return
netSalary
Variables which are not parameters or properties
must be defined locally.
8Creating Using Objects
- Always
- Declare variable to hold object
- Create object using new statement
- Call objects methods
Person aStudent
aStudent new Person( Ayse, 18)
aStudent.sayName()
Put this in method of another class, (e.g main
method)
9Creating Using Objects
Person aStudent aStudent new Person( Ayse,
18)
Person friend friend new Person( David, 22)
23
Good student
friend.increaseAge()aStudent.setComments( Good
student)
10Examples existing classes
Random die die new Random() int face
die.nextInt(6) 1 System.out.println( face)
StringTokenizer tokens tokens new
StringTokenizer( to be or not to be) while (
tokens.hasMoreTokens() ) aWord
tokens.nextToken() System.out.println(
aWord) System.out.println( done)
11Classes
- A class is a blueprint of its objects.
- We can create many objects from a single class.
- Creating an object from a class is called
instantiation, and an object is
an instance of a particular class. - Normally, an object is created from a class using
the new operator. - new ClassName( parameters )
- new Scanner(System.in) ? to create an Scanner
object - when a new operator is executed the constructor
method of the class is activated to create an
instance of that class, and that instance is
initialized by the constructor method. - The constructor method has same name as the class
and does not have any return type. - There are some short cuts to create objects of
certain pre-defined classes in Java API. - String class abc creates an object of
String class,
12Class Member Declarations
- Inside of a class, we may declare the following
class members - Fields/Properties data-variables declared in
the class. - Methods methods declared in the class.
- Constructors special methods to create objects
of the class, and to initialize fields. - The order of the declarations is not important,
but it is nice to use the following order. - class ClassName
- Fields
- Constructors
- Methods
-
13Accessibility Modifiers for Class Members
- There are four accessibility modifiers for class
members - public -- A public member is accessible by any
class. - private A private member is accessible only the
class itself. - protected A protected member is accessible by
the class itself, all its sub-classes, and all
the classes within the same package. -
- -- When no modifier is present, (by default)
the member is accessible by all the classes
within the same package. This accessibility
modifier (no modifier) is known as package
accessibility modifier.
14Accessibility Modifiers for Class Members (cont.)
public private protected package
The class itself yes yes yes yes
Classes in the same package yes no yes yes
Sub-classes in a different package yes no yes no
Non-subclasses in a different package yes no no no
15Fields
- Fields are also known as attributes.
- Fields are the data-variables declared in that
class. - A data-variable can be
- an instance variable (declared without using
keyword static), or - a class variable (declared using keyword static,
it is also known as a static variable). - An instance variable lives in an object of that
class, and each object of that class has its own
copy of that variable. - A static variable is a class-variable and there
is only one copy for it. All instances of that
class share that single copy. - A field is declared with a final modifier, it is
a constant and its value cannot be changed.
16Declarations of Fields
- A field declaration can be in the following form
- FieldModifiers Type FieldName1
Initializer1, ... , - FieldNamen Initializern
- Examples
- public int a
- int b1, c2
- private double x
- protected int y
- private static int x
- public static int y
- public final int CONST1 5
- private static final int CONST2 6
-
17Methods
- A method can be
- an instance method (declared without using
keyword static), or - a class method (declared using keyword static, it
is also known as a static method). - An instance method is associated with an object.
- If an instance method accesses an instance
variable, it accesses of the copy of that
instance variable in the current object. - It looks like that there are multiple copies of
an instance methods (one for each instance of
that class). - A static method is a class-method and there is
only one copy for it. - All instances of that class share that single
copy. - A static method cannot access an instance
variable or an instance method.
18Method Declaration
- A method declaration can be in the following
form - MethodModifiers ReturnType MethodName
- ( FormalParameterList ) Statements
- Examples
- public int m1(int x) ...
- public void m2(double x) ...
- private void m3(int x, double y) ...
- int m4() ...
- public static int m5() ...
- private static int m6() ...
19Creating Objects
- class C
- // fields
- private int x
- private double y
- // constructors
- public C() x1 y2.2
- // methods
- public void m1 (int val) xval
- public void m2 (double val) yval
-
- The constructor method must have the same name as
the class, and it does not have any return type
(not even void). - Variables x and y are instance-variables, and
they can be seen only by the methods of this
class.
20Creating Objects (cont.)
- In some other class, we may create the objects of
the class C. (If we want, we can also create the
objects of C in C too). - public class C2
- .... main (...)
- C obj1, obj2
- obj1 new C()
- obj2 new C()
-
- .
- .
-
x
obj1
1
y
2.2
obj2
1
x
y
2.2
21Dot Operator
- Once an object of a class is created, its
instance methods can be invoked using the dot
operator. - Of course, the method which will be invoked must
be accessible from that class. - To invoke a method object.methodname(
actual-parameters ) - Example (in a method of C2)
- obj1.m1(4)
- obj2.m1(3)
- obj1.m2(3.3)
- String s scanner.nextLine()
22Dot Operator (cont.)
- Using dot operator, we may also access fields.
- To access a field object.field
- Example (in a method of C2)
- obj1.x 4 ? it will not work, because x was
private - if C is declared as follows, the above assignment
will be okay. - class C
- public int x
- .
23Dot Operator (cont.)
- For static fields and methods, we can use the dot
operator. - We can access static fields and methods as
follows - ClassName.FieldName
- ClassName.MethodName(ActualParameters)
- To access static members, we do not need to
create an object from that class. - We may also access static members using objects
as follows. - Object.FieldName
- Object.MethodName(ActualParameters)
- All the objects will access the single copy of a
static member.
24Dot Operator (cont.)
- class C1
- public int x
- public static int y5
- public C1() x1
- public void setX(int val) xval
- public static void printY() System.out.println(
y y) -
- // in a method of some other class
- C1 o1,o2 o1.x 2
- C1.y 10 o2.x 3
- C1.x 10 ? ILLEGAL o1.y 4
- C1.printY() o2.y 5
- C1.setX(10) ? ILLEGAL C1.y 6
- o1 new C1() o1.setX(7)
- o2 new C1() o2.setX(8)
- o1.printY()
- o2.printY()
-
25Reference Assignment
- The act of assignment takes a copy of a value and
stores in a variable. - int x,y x 5 x 5
- x5 y6 yx y 6 y 5
- before assignment after assignment
- public C
- public int x,y
- public C() x1y2
-
- // in a method of another class
- C c1,c2
- c1new C()
- c2c1
- // c1 and c2 will point to the same object
26Aliases
- Two or more references may refer to the same
object. They are called aliases of each other. - Aliases can be useful, but they should be managed
carefully. - Affecting the object through one reference
affects its all aliases, because they refer to
the same object. - Example
- c1.x 5
- c2 is affected too.
27Garbage Collection
- Objects are allocated on the heap (a part of
memory space reserved for our programs to run). - When an object no longer has any valid references
to it, it can no longer be accessed by the
program. - In this case, it is useless, and it is called
garbage. - Java performs automatic garbage collection
periodically to collect garbage for future use.
28Variables
- In a Java program, we can access three kinds of
variables in the methods. - instance variables -- declared in the class
(without using static keyword) - class variables (static variables) - declared in
the class (with using static keyword) - local variables declared in a method or as its
formal parameters. - An instance method of a class can refer (just
using their names) to all instance variables,
all static variables declared in the class, and
all its local variables. - A static method of a class cannot refer to any
instance variable declared in that class. It can
only refer to static variables and its local
variables.
29Variables (cont.)
- class C
- int x
- static int y
- public void printX() System.out.println(x
x) - public static void printY() System.out.println(
y y) - public void m1(int a, int b)
- int cab
- xa yb
- printX() printY()
-
- public static m2(int a, int b)
- xa ? ILLEGAL
- yb
- printX() ? ILLEGAL
- printY()
-
-
30Call-by-Value and Call-by-Reference
- When an actual parameter is passed into a method,
its value is saved in the corresponding formal
parameter. - When the type of the formal parameter is a
primitive data type, the value of the actual
parameter is passed into the method and saved in
the corresponding formal parameter
(CALL-BY-VALUE). - When the type of the formal parameter is an
object data type, the reference to an object is
passed into the method and this reference is
saved in the corresponding formal parameter
(CALL-BY-REFERENCE). - In call-by-value, there is no way to change the
value of the corresponding actual parameter in
the method. - But in call-by-reference, we may change the value
of the corresponding actual parameter by changing
the content of the passed object.
31Call-by-Value and Call-by-Reference -- Example
- public class Test
- public static void main(String args) throws
IOException - int i1 MyInt n1,n2,n3
- n1new MyInt(3) n2new MyInt(5) n3new
MyInt(7) - ? values before chvalues
- chvalues(i,n1.ival,n2,n3)
- ? values after chvalues
- System.out.println(i-n1.ival-n2.ival-
n3.ival) -
- static void chvalues(int x, int y, MyInt w,
MyInt z) - xx-1 yy1
- w new MyInt(8)
- z.ival 9
-
-
- class MyInt
- public int ival
- public MyInt(int x) ivalx
32Call-by-Value and Call-by-Reference Example
in main
i
n1
n3
n2
1
3
7
5
9
in chvalues
X
y
x
z
w
1
3
0
4
8
33Object Reference this
- The keyword this can be used inside instance
methods to refer to the receiving object of the
method. - The receiving object is the object through which
the method is invoked. - The object reference this cannot occur inside
static methods. - Two common usage of this
- to pass the receiving object as a parameter
- to access fields shadowed by local variables.
- Each instance method runs under an object, and
this object can be accessible using this keyword.
34Passing this as a Parameter
- public class MyInt
- private int ival
- public MyInt(int val) ivalval
- public boolean isGreaterThan(MyInt o2)
- return (ival gt o2.ival)
-
- public boolean isLessThan(MyInt o2)
- return (o2.isGreaterThan(this))
-
-
- in some other place
- MyInt x1new MyInt(5), x2new MyInt(6)
- x1.isGreaterThan(x2)
- x1.isLessThan(x2)
35Accessing Shadowed Fields
- A field declared in a class can be shadowed
(hidden) in a method by a parameter or a local
variable of the same name. - public class T
- int x // an instance variable
- void m1(int x) ... // x is shadowed by a
parameter - void m2() int x ... // x is shadowed by a
local variable - To access a shadowed instance variable, we may
use this keyword. - public class T
- int x // an instance variable
- void changeX(int x) this.x x
36Time -- Example
- class Time
- private int hour, minute
- public Time (int h, int m) hour h minute
m - public void printTime ()
- if ((hour 0) (minute 0))
- System.out.print("midnight")
- else if ((hour 12) (minute 0))
- System.out.print("noon")
- else
- if (hour 0) System.out.print(12)
- else if (hour gt 12) System.out.print(hour-12
) - else System.out.print(hour)
-
- if (minute lt 10) System.out.print("0"
minute) - else System.out.print(""
minute) -
- if (hour lt 12) System.out.print("AM")
- else System.out.print("PM")
-
37Time Example (cont.)
- public Time addMinutes (int m)
- int totalMinutes (60hour minute m)
(2460) - if (totalMinutes lt 0)
- totalMinutes totalMinutes 2460
- return new Time(totalMinutes/60,
totalMinutes60) -
- public Time subtractMinutes (int m) return
addMinutes(-m) -
- public boolean priorTo (Time t)
- return ((hour lt t.hour) ((hour t.hour)
(minute lt t.minute))) -
-
- public boolean after (Time t2) return
t2.priorTo(this) -
-
38Time Example (cont.)
- public class Time2
- public static void main (String args)
- Time t1 new Time(0,0),
- t2 new Time(12,0),
- t3 new Time(8,45),
- t4 new Time(14,14)
- System.out.print("midnight - ")
t1.printTime() System.out.println() - System.out.print("noon - ")
t2.printTime() System.out.println() - System.out.print("845AM - ")
t3.printTime() System.out.println() - System.out.print("214PM - ")
t4.printTime() System.out.println() -
- t1 t1.addMinutes(460)
- System.out.print("400AM - ")
t1.printTime() System.out.println() -
- t1 t1.addMinutes(-260)
- System.out.print("200AM - ")
t1.printTime() System.out.println() -
-
39Time Example (cont.)
- t1 t1.addMinutes(-6)
- System.out.print("154AM - ")
t1.printTime() System.out.println() -
- t1 t1.addMinutes(-260)
- System.out.print("1154PM - ")
t1.printTime() System.out.println() -
- t1 t1.subtractMinutes(8)
- System.out.print("1146PM - ")
t1.printTime() System.out.println() -
- t1 t1.subtractMinutes(2460)
- System.out.print("1146PM - ")
t1.printTime() System.out.println() -
- System.out.println("true - "
t1.priorTo(new Time(23, 47))) - System.out.println("false - "
t1.priorTo(new Time(3, 47))) -
- System.out.println("true - " (new Time(23,
47)).after(t1)) - System.out.println("false - " (new Time(3,
47)).after(t1)) -
-
40Method Overloading
- Method overloading is the process of using the
same method name for multiple purposes. - The signature of each overloaded method must be
unique. - The signature of a method is based on the number,
the type and the order of the parameters (not
return type). - The compiler must be able to determine which
version of the method is invoked by analyzing
the parameters of a method call. - println is an overloaded method
- println(String s) ? System.out.println(abcd)
- println(int i) ? System.out.println(5)
41Method Overloading (cont.)
- The constructors of the classes are often
overloaded to provide multiple ways to set up a
new object. - class T
- private int x,y
- public T() x0 y0
- public T(int v1, int v2) xv1 yv2
-
- in somewhere else
- T o1 new T()
- T o2 new T(5,6)
42Overloaded Methods
- static void m(int x, int y) System.out.println("
m-i-i") - static void m() System.out.println("m-noarg")
- static void m(double x, double y)
System.out.println("m-d-d") - static void m(int x, double y)
System.out.println("m-i-d") - static void m(double x, int y)
System.out.println("m-d-i") - static void m(int x) System.out.println("m-i")
- to invoke this method
- m(1,2)
- m()
- m(1.1,2.2)
- m(1,2.2)
- m(1.1,2)
- m(1)
43Overloaded Methods
- public class Test3
- static void m() System.out.println("m-noarg")
- static void m(int x, int y)
System.out.println("m-i-i") - static void m(double x, double y)
System.out.println("m-d-d") - static void m(int x, double y)
System.out.println("m-i-d") - static void m(double x, int y)
System.out.println("m-d-i") - static void m(int x) System.out.println("m-i"
) - static void m(short x) System.out.println("m-
s") - static void m(byte x) System.out.println("m-b
") - public static void main(String args)
- System.out.print("m(1,2) -- ") m(1,2)
- System.out.print("m() -- ") m()
- System.out.print("m(1.1,2.2) -- ") m(1.1,2.2)
- System.out.print("m(1,2.2) -- ") m(1,2.2)
- System.out.print("m(1.1,2) -- ") m(1.1,2)
- System.out.print("m(1) -- ") m(1)
- System.out.print("m((byte)1) -- ") m((byte)1)
- System.out.print("m((short)1) -- ")
m((short)1) - System.out.print("m((int)1) -- ") m((int)1)
44RationalNum -- Constructors
- class RationalNum
- // Fields a rational number is
numerator/denominator - private int numerator, denominator
- // Constructors Assume that parameters are
positive - public RationalNum(int n, int d)
- int gcd gcdivisor(n,d)
- numerator n/gcd
- denominator d/gcd
-
- public RationalNum(int n)
- numerator n
- denominator 1
-
- public RationalNum()
- numerator 0
- denominator 1
-
45RationalNum -- gcdivisor
- // gcdivisor -- finds the greatest common
divisor of the given two integers - private static int gcdivisor(int n1, int n2)
- if (n10 n20) return 1
- else if (n10) return n2
- else if (n20) return n1
- else // they are not zero, Apply Euclid's
algorithm for these positive numbers - while (n1 ! n2)
- if (n1gtn2) n1n1-n2
- else n2n2-n1
-
- return n1
-
-
-
-
46RationalNum add and subtract
- // add method -- add the current rational
number with another rational number or an
integer. - public RationalNum add(RationalNum r2)
- return(new RationalNum(numeratorr2.denominato
rr2.numeratordenominator, - denominatorr2.denominator
)) -
-
- public RationalNum add(int n2)
- return(new RationalNum(numeratorn2denomina
tor,denominator)) -
-
- // subtract method -- subtract another rational
number or an integer fromthe current rational
number. - public RationalNum subtract(RationalNum r2)
- return(new RationalNum(numeratorr2.denominato
r-r2.numeratordenominator, - denominatorr2.denominat
or)) -
-
- public RationalNum subtract(int n2)
- return(new RationalNum(numerator-n2denomina
tor,denominator)) -
47RationalNum compareTo and toString
- // compareTo -- compare the current rational
number with another rational number or an
integer. - // returns 0 if they are equal returns 1 if the
current rational number is less than the given
parameter - // returns 1 otherwise
- public int compareTo(RationalNum r2)
- if (numeratorr2.denominator lt
r2.numeratordenominator) return -1 - else if (numeratorr2.denominator
r2.numeratordenominator) return 0 - else return 1
-
-
- public int compareTo(int n2)
- if (numerator lt n2denominator) return -1
- else if (numerator n2denominator) return
0 - else return 1
-
-
- // toString method -- the string representation
of a rational number is numerator/denominator. - public String toString()
- return(numerator"/"denominator)
-
48RationalNumTest
- // Demo class
- public class RationalNumTest
- public static void main( String args ) throws
IOException - RationalNum r1,r2
- int n1,n2,d1,d2
- BufferedReader stdin new BufferedReader(new
InputStreamReader(System.in)) -
- System.out.println("The value of new
RationalNum() " (new RationalNum())) - System.out.println("The value of new
RationalNum(3) " (new RationalNum(3))) - System.out.println("The value of new
RationalNum(4,6) " (new RationalNum(4,6))) -
- System.out.print("Enter the first numerator
") System.out.flush() - n1 Integer.parseInt(stdin.readLine().trim())
- System.out.print("Enter the first
denominator ") System.out.flush() - d1 Integer.parseInt(stdin.readLine().trim())
-
- System.out.print("Enter the second numerator
") System.out.flush() - n2 Integer.parseInt(stdin.readLine().trim())
49RationalNumTest (cont.)
-
- r1 new RationalNum(n1,d1) r2 new
RationalNum(n2,d2) -
- System.out.println("r1 " r1)
System.out.println("r2 " r2) -
- System.out.println("r1.add(r2) "
r1.add(r2)) - System.out.println("r1.add(3) "
r1.add(3)) -
- System.out.println("r1.subtract(r2) "
r1.subtract(r2)) - System.out.println("r1.subtract(3) "
r1.subtract(3)) -
- System.out.println("r1.compareTo(r2) "
r1.compareTo(r2)) - System.out.println("r1.compareTo(3) "
r1.compareTo(3)) -
-
50An Example with Static Fields
- class C
- private static int count 0
- private int objIndex
- public C() countcount1 objIndexcount
- public static int numOfObjs() return count
- public int objID() return objIndex
-
- // in a method of some other class
- C o1,o2,o3
- o1 new C()
- o2 new C()
- o3 new C()
- System.out.println(o1.objID())
- System.out.println(o2.objID())
- System.out.println(o3.objID())
- C.numOfObjs()
-