Describing the world 1 Describe a particular person
Describing the world (1) • Describe a particular person – Ayse has long blond hair, green eyes, is 1. 63 m tall, weighs 56 Kg and studies computer engineering. Now lying down asleep. – Mehmet studies electronics, has short black hair and brown eyes. He is 180 cm and 75 kilos. Now running to class! • Notice how all have specific values of – name, height, weight, eye color, state, … Individual 9/10/2020 Category CS 101 - Algorithms & Programming I 1
Describing the world (2) • Type/category determine an object’s 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 Category 9/10/2020 Individual CS 101 - Algorithms & Programming I 2
Java OOP terminology • Class - Category – Properties/states – Functionality/Services (examines/alters state) n 9/10/2020 data methods object - Individual/unique thing (an instance of a class) n Particular value for each property/state n & functionality of all members of class. CS 101 - Algorithms & Programming I 3
Java OOP Software • Software System Created (instantiated) from class definitions – Set of objects – Which interact with each other 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 object’s methods! Person Ayse David: Say your name 9/10/2020 CS 101 - Algorithms & Programming I David “David” 4
In more detail • Create & manipulate person objects Person name, age, salary, comments say. Name, get. Net. Salary get. Comments set. Comments increase. Age … 9/10/2020 Name: “Ayse” Age: 18 Salary: 500 Comments: “Good student” CS 101 - Algorithms & Programming I Name: “David” Age: 22 Salary: 2000 Comments: “Teaches CS 101” 5
Coding Java Classes // header public class Person { // properties // constructors // methods } String int double String name; age; salary; comments; public Person( String the. Name, int the. Age ) { name = the. Name; age = the. Age; comments = “”; } public void say. Name() { System. out. println( name); } 9/10/2020 CS 101 - Algorithms & Programming I 6
Coding Java Classes public String get. Name() { return name; } public String get. Comments() { return comments; } public void set. Comments( String some. Text) { comments = some. Text; } public void increase. Age() { age = age + 1; } public double get. Net. Salary() { double net. Salary; net. Salary = salary - TAX; return net. Salary; } 9/10/2020 CS 101 - Algorithms & Programming I “get” & “set” methods for some properties (no set. Name!) Variables which are not parameters or properties must be defined locally. 7
Creating & Using Objects • Always – Declare variable to “hold” object – Create object using “new” statement – Call object’s methods Person a. Student; a. Student = new Person( “Ayse”, 18); a. Student. say. Name(); Put this in method of another class, (e. g main method) 9/10/2020 a. Student {Person} name: “Ayse” age: 18 salary: 0. 0 comments: “” CS 101 - Algorithms & Programming I 8
Creating & Using Objects Person a. Student; a. Student = new Person( “Ayse”, 18); Person friend; friend = new Person( “David”, 22); name: a. Student {Person} name: “Ayse” age: 18 salary: 0. 0 friend {Person} “David” age: 22 23 salary: 0. 0 comments: “” “Good student” friend. increase. Age(); a. Student. set. Comments( “Good student”); 9/10/2020 CS 101 - Algorithms & Programming I 9
Examples: existing classes • Random class Random die; die = new Random(); int face = die. next. Int(6) + 1; System. out. println( face); n String. Tokenizer class String. Tokenizer tokens; tokens = new String. Tokenizer( “to be or not to be”); while ( tokens. has. More. Tokens() ) { a. Word = tokens. next. Token(); System. out. println( a. Word); } System. out. println( “done”); 9/10/2020 CS 101 - Algorithms & Programming I 10
Classes • 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 Class. Name( 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, Spring 2003 COP 3330 Object Oriented Programming 11
Class 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 Class. Name { Fields Constructors Methods } 9/10/2020 CS 101 - Algorithms & Programming I 12
Accessibility 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. 9/10/2020 CS 101 - Algorithms & Programming I 13
Accessibility Modifiers for Class Members (cont. ) 9/10/2020 public private protected The class itself yes yes Classes in the same package yes no yes Sub-classes in a different package yes no Non-subclasses in a different package yes no no no CS 101 - Algorithms & Programming I package 14
Fields • 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. 9/10/2020 CS 101 - Algorithms & Programming I 15
Declarations of Fields • A field declaration can be in the following form: [Field. Modifiers] Type Field. Name 1 [ = Initializer 1], . . . , Field. Namen [ = Initializern] ; Examples: public int a; int b=1, c=2; private double x; protected int y; private static int x; public static int y; public final int CONST 1 = 5; private static final int CONST 2 = 6; 9/10/2020 CS 101 - Algorithms & Programming I 16
Methods • 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. 9/10/2020 CS 101 - Algorithms & Programming I 17
Method Declaration • A method declaration can be in the following form: [Method. Modifiers] Return. Type Method. Name ( [Formal. Parameter. List] ) { Statements } Examples: public int m 1(int x) {. . . } public void m 2(double x) {. . . } private void m 3(int x, double y) {. . . } int m 4() {. . . } public static int m 5() {. . . } private static int m 6() {. . . } 9/10/2020 CS 101 - Algorithms & Programming I 18
Creating Objects class C { // fields private int x; private double y; // constructors public C() { x=1; y=2. 2; } // methods public void m 1 (int val) { x=val; } public void m 2 (double val) { y=val; } } • 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. 9/10/2020 CS 101 - Algorithms & Programming I 19
Creating 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). 9/10/2020 obj 1 obj 2 CS 101 - Algorithms & Programming I x 1 y 2. 2 x public class C 2 {. . main (. . . ) { C obj 1, obj 2; obj 1 = new C(); obj 2 = new C(); }. . } 1 y 2. 2 20
Dot 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 C 2) obj 1. m 1(4); obj 2. m 1(3); obj 1. m 2(3. 3); String s = scanner. next. Line(); 9/10/2020 CS 101 - Algorithms & Programming I 21
Dot Operator (cont. ) • Using dot operator, we may also access fields. • To access a field: object. field Example: (in a method of C 2) obj 1. 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; . } 9/10/2020 CS 101 - Algorithms & Programming I 22
Dot Operator (cont. ) • For static fields and methods, we can use the dot operator. • We can access static fields and methods as follows: Class. Name. Field. Name Class. Name. Method. Name(Actual. Parameters) • 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. Field. Name Object. Method. Name(Actual. Parameters) • All the objects will access the single copy of a static member. 9/10/2020 CS 101 - Algorithms & Programming I 23
Dot Operator (cont. ) class C 1 { public int x; public static int y=5; public C 1() { x=1; } public void set. X(int val) { x=val; } public static void print. Y() { System. out. println(“y: “ + y); } } // in a method of some other class C 1 o 1, o 2; o 1. x = 2; C 1. y = 10; o 2. x = 3; C 1. x = 10; ILLEGAL o 1. y = 4; C 1. print. Y(); o 2. y = 5; C 1. set. X(10); ILLEGAL C 1. y = 6; o 1 = new C 1(); o 1. set. X(7); o 2 = new C 1(); o 2. set. X(8); o 1. print. Y(); o 2. print. Y(); 9/10/2020 CS 101 - Algorithms & Programming I 24
Reference Assignment • The act of assignment takes a copy of a value and stores in a variable. int x, y; x=5; y=6; y=x; x 5 y 6 before assignment x 5 y 5 after assignment public C { public int x, y; public C() {x=1; y=2; } } // in a method of another class C c 1, c 2; c 1=new C(); c 2=c 1; // c 1 and c 2 will point to the same object 9/10/2020 CS 101 - Algorithms & Programming I 25
Aliases • 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: c 1. x = 5; • c 2 is affected too. 9/10/2020 CS 101 - Algorithms & Programming I 26
Garbage 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. 9/10/2020 CS 101 - Algorithms & Programming I 27
Variables • 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. 9/10/2020 CS 101 - Algorithms & Programming I 28
Variables (cont. ) class C { int x; static int y; public void print. X() { System. out. println(“x: “+x); } public static void print. Y() { System. out. println(“y: “+y); } public void m 1(int a, int b) { int c=a+b; x=a; y=b; print. X(); print. Y(); } public static m 2(int a, int b) { x=a; ILLEGAL y=b; print. X(); ILLEGAL print. Y(); } } 9/10/2020 CS 101 - Algorithms & Programming I 29
Call-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. 9/10/2020 CS 101 - Algorithms & Programming I 30
Call-by-Value and Call-by-Reference -- Example public class Test { public static void main(String[] args) throws IOException { int i=1; My. Int n 1, n 2, n 3; n 1=new My. Int(3); n 2=new My. Int(5); n 3=new My. Int(7); values before chvalues(i, n 1. ival, n 2, n 3); values after chvalues System. out. println(i+”-”+n 1. ival+”-”+n 2. ival+”-”+n 3. ival); } static void chvalues(int x, int y, My. Int w, My. Int z) { x=x-1; y=y+1; w = new My. Int(8); z. ival = 9; } } class My. Int { public int ival; public My. Int(int x) { ival=x; } } 9/10/2020 CS 101 - Algorithms & Programming I 31
Call-by-Value and Call-by-Reference – Example in main i 1 in chvalues x 10 = n 1 n 2 n 3 ival 5 ival 79 = y 34 = X w z ival 8 9/10/2020 CS 101 - Algorithms & Programming I 32
Object 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. 9/10/2020 CS 101 - Algorithms & Programming I 33
Passing this as a Parameter public class My. Int { private int ival; public My. Int(int val) { ival=val; } public boolean is. Greater. Than(My. Int o 2) { return (ival > o 2. ival); } public boolean is. Less. Than(My. Int o 2) { return (o 2. is. Greater. Than(this)); } } in some other place My. Int x 1=new My. Int(5), x 2=new My. Int(6); x 1. is. Greater. Than(x 2); x 1. is. Less. Than(x 2); 9/10/2020 CS 101 - Algorithms & Programming I 34
Accessing 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 m 1(int x) {. . . } void m 2() { int x; . . . } // x is shadowed by a parameter // 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 change. X(int x) { this. x = x; } } 9/10/2020 CS 101 - Algorithms & Programming I 35
Time -- Example class Time { private int hour, minute; public Time (int h, int m) { hour = h; minute = m; } public void print. Time () { 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 > 12) System. out. print(hour-12); else System. out. print(hour); if (minute < 10) System. out. print(": 0" + minute); else System. out. print(": " + minute); if (hour < 12) System. out. print("AM"); else System. out. print("PM"); } } 9/10/2020 CS 101 - Algorithms & Programming I 36
Time – Example (cont. ) public Time add. Minutes (int m) { int total. Minutes = (60*hour + minute + m) % (24*60); if (total. Minutes < 0) total. Minutes = total. Minutes + 24*60; return new Time(total. Minutes/60, total. Minutes%60); } public Time subtract. Minutes (int m) { return add. Minutes(-m); } public boolean prior. To (Time t) { return ((hour < t. hour) || ((hour == t. hour) && (minute < t. minute))); } public boolean after (Time t 2) { return t 2. prior. To(this); } } 9/10/2020 CS 101 - Algorithms & Programming I 37
Time – Example (cont. ) public class Time 2 { public static void main (String[] args) { Time t 1 = new Time(0, 0), t 2 = new Time(12, 0), t 3 = new Time(8, 45), t 4 = new Time(14, 14); 9/10/2020 System. out. print("midnight - "); System. out. print("noon - "); System. out. print("8: 45 AM - "); System. out. print("2: 14 PM - "); t 1. print. Time(); t 2. print. Time(); t 3. print. Time(); t 4. print. Time(); t 1 = t 1. add. Minutes(4*60); System. out. print("4: 00 AM - "); t 1. print. Time(); System. out. println(); t 1 = t 1. add. Minutes(-2*60); System. out. print("2: 00 AM - "); t 1. print. Time(); System. out. println(); CS 101 - Algorithms & Programming I System. out. println(); 38
Time – Example (cont. ) t 1 = t 1. add. Minutes(-6); System. out. print("1: 54 AM - "); t 1. print. Time(); System. out. println(); t 1 = t 1. add. Minutes(-2*60); System. out. print("11: 54 PM - "); t 1. print. Time(); System. out. println(); t 1 = t 1. subtract. Minutes(8); System. out. print("11: 46 PM - "); t 1. print. Time(); System. out. println(); t 1 = t 1. subtract. Minutes(24*60); System. out. print("11: 46 PM - "); t 1. print. Time(); System. out. println("true - " + t 1. prior. To(new Time(23, 47))); System. out. println("false - " + t 1. prior. To(new Time(3, 47))); System. out. println("true - " + (new Time(23, 47)). after(t 1)); System. out. println("false - " + (new Time(3, 47)). after(t 1)); } } 9/10/2020 CS 101 - Algorithms & Programming I 39
Method 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); 9/10/2020 CS 101 - Algorithms & Programming I 40
Method 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() { x=0; y=0; } public T(int v 1, int v 2) { x=v 1; y=v 2; } } in somewhere else T o 1 = new T(); T o 2 = new T(5, 6); 9/10/2020 CS 101 - Algorithms & Programming I 41
Overloaded Methods static static void void m(int x, int y) { System. out. println("m-i-i"); } m() { System. out. println("m-noarg"); } m(double x, double y) { System. out. println("m-d-d"); } m(int x, double y) { System. out. println("m-i-d"); } m(double x, int y) { System. out. println("m-d-i"); } m(int x) { System. out. println("m-i"); } to invoke this method m(1, 2); m(1. 1, 2); m(1); 9/10/2020 CS 101 - Algorithms & Programming I 42
Overloaded Methods public class Test 3 { 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); } } 9/10/2020 CS 101 - Algorithms & Programming I 43
Rational. Num -- Constructors class Rational. Num { // Fields: a rational number is numerator/denominator private int numerator, denominator; // Constructors – Assume that parameters are positive public Rational. Num(int n, int d) { int gcd = gcdivisor(n, d); numerator = n/gcd; denominator = d/gcd; } public Rational. Num(int n) { numerator = n; denominator = 1; } public Rational. Num() { numerator = 0; denominator = 1; } 9/10/2020 CS 101 - Algorithms & Programming I 44
Rational. Num -- gcdivisor // gcdivisor -- finds the greatest common divisor of the given two integers private static int gcdivisor(int n 1, int n 2) { if (n 1==0 && n 2==0) return 1; else if (n 1==0) return n 2; else if (n 2==0) return n 1; else { // they are not zero, Apply Euclid's algorithm for these positive numbers while (n 1 != n 2) { if (n 1>n 2) n 1=n 1 -n 2; else n 2=n 2 -n 1; } return n 1; } } 9/10/2020 CS 101 - Algorithms & Programming I 45
Rational. Num – add and subtract // add method -- add the current rational number with another rational number or an integer. public Rational. Num add(Rational. Num r 2) { return(new Rational. Num(numerator*r 2. denominator+r 2. numerator*denominator, denominator*r 2. denominator)); } public Rational. Num add(int n 2) { return(new Rational. Num(numerator+n 2*denominator, denominator)); } // subtract method -- subtract another rational number or an integer fromthe current rational number. public Rational. Num subtract(Rational. Num r 2) { return(new Rational. Num(numerator*r 2. denominator-r 2. numerator*denominator, denominator*r 2. denominator)); } public Rational. Num subtract(int n 2) { return(new Rational. Num(numerator-n 2*denominator, denominator)); } 9/10/2020 CS 101 - Algorithms & Programming I 46
Rational. Num – compare. To and to. String // compare. To -- 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 compare. To(Rational. Num r 2) { if (numerator*r 2. denominator < r 2. numerator*denominator) return -1; else if (numerator*r 2. denominator == r 2. numerator*denominator) return 0; else return 1; } public int compare. To(int n 2) { if (numerator < n 2*denominator) return -1; else if (numerator == n 2*denominator) return 0; else return 1; } // to. String method -- the string representation of a rational number is numerator/denominator. public String to. String() { return(numerator+"/"+denominator); } 9/10/2020 CS 101 - Algorithms & Programming I 47
Rational. Num. Test // Demo class public class Rational. Num. Test { public static void main( String args[] ) throws IOException { Rational. Num r 1, r 2; int n 1, n 2, d 1, d 2; Buffered. Reader stdin = new Buffered. Reader(new Input. Stream. Reader(System. in)); System. out. println("The value of new Rational. Num(): " + (new Rational. Num())); System. out. println("The value of new Rational. Num(3): " + (new Rational. Num(3))); System. out. println("The value of new Rational. Num(4, 6): " + (new Rational. Num(4, 6))); System. out. print("Enter the first numerator: "); System. out. flush(); n 1 = Integer. parse. Int(stdin. read. Line(). trim()); System. out. print("Enter the first denominator: "); System. out. flush(); d 1 = Integer. parse. Int(stdin. read. Line(). trim()); System. out. print("Enter the second numerator: "); System. out. flush(); n 2 = Integer. parse. Int(stdin. read. Line(). trim()); System. out. print("Enter the second denominator: "); System. out. flush(); d 2 = Integer. parse. Int(stdin. read. Line(). trim()); 9/10/2020 CS 101 - Algorithms & Programming I 48
Rational. Num. Test (cont. ) r 1 = new Rational. Num(n 1, d 1); r 2 = new Rational. Num(n 2, d 2); System. out. println("r 1: " + r 1); System. out. println("r 2: " + r 2); System. out. println("r 1. add(r 2): " + r 1. add(r 2)); System. out. println("r 1. add(3): " + r 1. add(3)); System. out. println("r 1. subtract(r 2): " + r 1. subtract(r 2)); System. out. println("r 1. subtract(3): " + r 1. subtract(3)); System. out. println("r 1. compare. To(r 2): " + r 1. compare. To(r 2)); System. out. println("r 1. compare. To(3): " + r 1. compare. To(3)); } } 9/10/2020 CS 101 - Algorithms & Programming I 49
An Example with Static Fields class C { private static int count = 0; private int obj. Index; public C() { count=count+1; obj. Index=count; } public static int num. Of. Objs() { return count; } public int obj. ID() { return obj. Index; } } // in a method of some other class C o 1, o 2, o 3; o 1 = new C(); o 2 = new C(); o 3 = new C(); System. out. println(o 1. obj. ID()); System. out. println(o 2. obj. ID()); System. out. println(o 3. obj. ID()); C. num. Of. Objs(); 9/10/2020 CS 101 - Algorithms & Programming I 50
- Slides: 50