Title: Classes
1Classes
- 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 InputStreamReader(System.in) ? to create
an InputStreamReader 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 - array classes int x 5,2,1 creates
an int array object with size 3 and initializes
that array.
2Class Declaration
- ClassAccesibilityModifiers OtherClassModifiers
class ClassName - extends SuperClass
- implements Interface1,...,Interfacen
-
- ClassMemberDeclarations
3Class Accessibility Modifiers
- There are two class accessibility modifiers that
are valid for regular classes (i.e. not nested
classesmore on this later) - public A public class is accessible by any
class. - When no modifier is present, (by default) the
class is accessible by all the classes within the
same package. This accessibility modifier (no
modifier) is known as package accessibility
modifier. - For those interested, valid modifiers for nested
classes can be found on page 605 of The Object
of Java.
4Other Class Modifiers
- abstract
- - An abstract class contains abstract methods.
- - An abstract method is an unimplemented
method. - (we will talk abstract classes later).
- final
- - A final class may not have sub-classes.
5Class Member Declarations
- Inside of a class, we may declare the following
class members - Fields 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. - Inner Classes -- classes nested in the class. An
inner class cannot have any other inner class.
This means that the nesting is only one level.
(we are not going to talk too much about inner
classes). - The order of the declarations is not important,
but it is nice to use the following order. - class ClassName
- Fields
- Constructors
- Methods
-
6Accessibility 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. Note Many
times, this will be a better choice than private. -
- 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.
7Accessibility Modifiers for Class Members (cont.)
8Fields
- 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.
9Declarations 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
-
10Methods
- 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. - A method is declared with a final modifier, it
cannot be overridden in the sub-classes of the
class.
11Method 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) ...
- protected void m4() ...
- int m5() ...
- private final void m6() ...
- public static int m7() ...
- private static final m8() ...
12Creating 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 methods of this class.
13Creating 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
14Dot 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 stdin.readLine()
- int a Integer.parseInt(stdin.readLine().trim())
15Dot 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
- .
16Dot 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.
17Dot Operator (cont.)
- class C1
- public int x
- public static int y5
- public C1() x1
- public void setX(int val) xval
- public static 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()
-
18Another 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()
-
19Reference 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
20Aliases
- 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.
21Garbage 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.
22Variables
- 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.
23Variables (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()
-
-
24Methods
- A class contains methods.
- A method is a group of statements that are given
a name. - Each method will be associated with a particular
class (or with an instance of that class). - We may define methods and invoke them with
different parameters. When its parameters are
different, their behavior will be different.
25Method Definition
- All methods follow the same syntax when they are
defined - return-type method-name ( formal-parameter-lis
t ) - statements
-
- return-type indicates the type of the value
returned from this method. - method-name is the name of this method (an
identifier), - formal-parameter-list indicates
- how many parameters will be taken by this method
- the names of the formal parameters (how do we use
them in the inside of this method) - the data types of these parameters
- statements are the executable (and declarations
for local variables) of this method. These
statements will be executed when this method is
invoked.
26Method Definition -- Example
- return-type method-name formal-parameter-list
- int thirdPower(int num)
- int cube local variable declaration
- cube numnumnum
- return cube return statement
-
27Return-Type and Return Statement
- The return type can be any data type (a primitive
data type or an object data type) or void. - A return statement will be in the following form
- return expression where the type of the
expression must be the same as the return
type of that method. - If the return type of a method is different from
void, that method must contain at least one
return statement. - When a return statement is executed in that
method , we exit from that method by returning
the value of the expression in that return
statement. - Normally, method calls for these methods are
parts of expressions. - If the return type of a method is void, that
method does not need to have a return statement. - In this case, when the last statement in that
method is executed, we return from that method.
(Or, it may contain a return statement without an
expression return ) - Normally, a method call for the method with void
return type is a statement.
28Parameters
- A method accept zero or more parameters
- Each parameter in the parameter list is specified
by its type and name. - The parameters in the method definition are
called formal parameters. - The values passed to a method when it is invoked
are called actual parameters. - The first actual parameter corresponds to the
first formal parameter, the second actual
parameter to second formal parameter, and so on.. - The type of the actual parameter must be
assignment compatible with the corresponding
formal parameter.
29Call-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.
30Call-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
31Call-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
32Object 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.
33Passing 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)
34Accessing 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 able 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
35Time -- 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")
-
36Time 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) -
-
37Time 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() -
-
38Time 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)) -
-
39Combination-Permutation Example
- import java.io.
- public class CombPerm
- public static void main(String args)throws
IOException - int n,r,combVal,permVal
- BufferedReader stdin
- new BufferedReader (new
InputStreamReader (System.in)) - System.out.print("An Integer Number (N)gt
") - System.out.flush()
- n Integer.parseInt(stdin.readLine().trim()
) - System.out.print("Another Integer Number
(R)gt ") - System.out.flush()
- r new Integer(stdin.readLine().trim()).int
Value() - // Calculate Combination and permutation
- combVal comb(n,r)
- permVal perm(n,r)
40Combination-Permutation Example (cont.)
- // C(n,r) n! / (r! (n-r)!)
- static int comb(int n, int r)
- return fact(n)/(fact(r)fact(n-r))
-
- // P(n,r) n! / (n-r)!
- static int perm(int n, int r)
- return fact(n)/fact(n-r)
-
- // Factorial
- static int fact(int n)
- int i,val
- val 1 i1
- while (iltn)
- val vali
- i i 1
-
41Method 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)
42Method 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)
43Overloaded 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)
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)) -
-