some quick reviews of java. background java was developed in the early 90s by sun microsystems java...

122
Some Quick Reviews of Java

Upload: shavonne-sanders

Post on 23-Dec-2015

220 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Some Quick Reviews of Java

Page 2: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Background• Java was developed in the early 90s by Sun Microsystems

• Java is a high-level language

• Java programs are portable across platforms– Each program is translated into Java byte-code– Each machine has a Java Virtual Machine (JVM) which knows how to

execute Java byte-code.– Can be either stand-alone programs or applets.

• Java is object-oriented

• Suggested IDE (Eclipse, Jbuilder, Visual Java, etc.)

Page 3: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Java and C/C++Include existing codes or libraries

#include <…>

or#include “…”

C/C++ java

import package1.sub-package.classname

or import package.sub-package.*

Page 4: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Java and C/C++Screen I/O streams

#include <stdio.h>

printf(“<formatting>”, var1, var2…);scanf(“<formatting>”, &var1, &var2…);

Cjava

System.out.printf(“<formatting>”, var1, var2,…);System.out.print(String…); //in same lineSystem.out.println(String…); //next line

import java.util.Scanner //for inputScanner keyboard = new Scanner(System.in);int var1 = keyboard.nextInt();double var2 = keyboard.nextDouble();String s1 = keyboard.next(); // read one wordString s2 = keyboard.nextline(); //read one line

C++

#include <iostream>

cout << <constant string | varables> << endl;cin >> variable

Page 5: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Java and C/C++What are similar or same

• Basic types, e.g. int, float, double, char, … automatic type conversionbyteshortintlongfloatdouble char

• Basic operations, e.g. “+”, “-”, “*”, “/”, “++”, “--”, “>”, “<“, “==”, “!=“…

• Flow controls• if-else statement, if - else if - else statement• for loops• while loops, do-while loops• switch-case statement

Page 6: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Java and C/C++What are similar or same

• Basic types, e.g. int, float, double, char, … automatic type conversion

• Basic operations, e.g. “+”, “-”, “*”, “/”, “++”, “--”, “>”, “<“, “==”, “!=“…

• Flow controls• if-else statement, if - else if - else statement• for loops• while loops, do-while loops• switch-case statement

Java does not have pointers!

Page 7: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Java and C/C++execution entrance

#include <stdio.h>

void main (<argument list>){……}

C/C++ java

import package.class…

public class class_name /* must have the same name as the file*/{ public static void main(<argument list>)

{ ……}

}

Page 8: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Java and C/C++

Local and global variables

In C/C++, the variables defined in a function or other block enclosed by a pair of braces “{ }” are local.The variables declared outside any methods and classes are global.

In Java, all variables are local. There are NO global variables, i.e. all the variables have to be declared within a method/ function or a class.Also, the variables declared in a block “{ }” cannot be repeated in the same function.

Page 9: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Java and C/C++

Local and global variables

In C/C++, the variables defined in a function or other block enclosed by a pair of braces “{ }” are local.The variables declared outside any methods and classes are global.

In Java, all variables are local. There are NO global variables, i.e. all the variables have to be declared within a method/function or a class.Also, the variables declared in a block “{ }” cannot be repeated in the same function.

void func(){ { int i; … } int i; //OK ……}

public void func(){ { int i; … } int i; //illegal! ……}

Page 10: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Class in Java

Page 11: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

What we have learned• Classes are the most important language feature that make object-

oriented programming (OOP) possible.– Combination of both attributes and behaviors– Can be used to generate many objects with the same behaviors– Information hidden and encapsulation

Page 12: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Similar in Java, yet different

• Classes are the most important language feature that make object-oriented programming (OOP) possible.– Combination of both attributes and behaviors– Can be used to generate many objects with the same behaviors– Information hidden and encapsulation

• Programming in Java consists of defining a number of classes– Every program is a class– All helping software consists of classes– All programmer-defined types are classes

• Classes are central to Java

Page 13: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

How to define a class in Java?

How did we do that in C++?

Page 14: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

How to define a class in Java?

How did we do that in C++?

class class_name{public: //member func.…private: // attribute list};

Page 15: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

How to define a class in Java?

How did we do that in C++?

class class_name{public: //member func.…private: // attribute list};

How should we do that in Java?

Page 16: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

How to define a class in Java?

How did we do that in C++?

class class_name{public: //member func.…private: // attribute list};

How should we do that in Java?

public class class_name{public member func1public member func2…private member var1private member var2…}

No semi-column!

Page 17: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

One Example

class DayOfYear{public: DayOfYear(); DayOfYear(int monthVal, int dayVal); void input(); void output();private: int month, day;};

Recall the day of the year example:

This is what we did in C++ How should we implement it in java?

Page 18: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

One Example

class DayOfYear{public: DayOfYear(); DayOfYear(int monthVal, int dayVal); void input(); void output();private: int month, day;};

Recall the day of the year example:

This is what we did in C++ How should we implement it in java?

public class DayOfYear{public DayOfYear(){}public DayOfYear(int monthVal, int dayVal){}public void input(){}public void output(){}private int month, day;}

Page 19: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

One Example

DayOfYear::DayOfYear(){}

DayOfYear::DayOfYear(int monthVal, int dayVal):month(monthVal),day(dayVal){}

void DayOfYear::input(){……}

void DayOfYear::output(){}

How do we implement the member functions?

This is what we did in C++Likely in a different file.

This is how we implement it in java.

public class DayOfYear{public DayOfYear(){}public DayOfYear(int monthVal, int dayVal){}public void input(){}public void output(){}private int month, day;}

Page 20: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

class in javapublic class DayOfYear{

private int month, day;

public DayOfYear(){ month = 0; day = 0;}

public DayOfYear(int monthVal, int dayVal){ month = monthVal; day = dayVal;}

public void input(int mVal, int dVal){ month = mVal; day = dVal;}

public void output(){System.out.print(“month=“+month + “; ”); System.out.println(“day=“+day);}

}

need to specify the modifier of the class

Page 21: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

class in javapublic class DayOfYear{

private int month, day;

public DayOfYear(){ month = 0; day = 0;}

public DayOfYear(int monthVal, int dayVal){ month = monthVal; day = dayVal;}

public void input(int mVal, int dVal){ month = mVal; day = dVal;}

public void output(){System.out.print(“month=“+month + “; ”); System.out.println(“day=“+day);}

}

need to specify the modifier of the class

Each member function needs a modifier

Page 22: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

class in javapublic class DayOfYear{

private int month, day;

public DayOfYear(){ month = 0; day = 0;}

public DayOfYear(int monthVal, int dayVal){ month = monthVal; day = dayVal;}

public void input(int mVal, int dVal){ month = mVal; day = dVal;}

public void output(){System.out.print(“month=“+month + “; ”); System.out.println(“day=“+day);}

}

need to specify the modifier of the class

Each member function needs a modifier

Declaration and definition in one place,e.g. in a ‘.java’ file that has same name as the class.

Page 23: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Create Objects

public class DayOfYearDemo{

public void main(){ DayOfYear date1, date2; //declaration date1 = new DayofYear(); //creates an object date2 = new DayofYear(2, 25); ……}

}

Use new operator!

invoke constructor!

Page 24: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Create Objects

public class DayOfYearDemo{

public void main(){ DayOfYear date1, date2; //declaration date1 = new DayofYear(); //creates an object date2 = new DayofYear(2, 25); ……}

}

Use new operator!

Note that this is different from C++!

DayOfYear date1(2, 25);DayOfYear *date2 = new DayofYear();

invoke constructor!

Page 25: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Constructors

public class DayOfYear{

public DayOfYear(){ month = day = 1;}public DayOfYear(int monthVal, int dayVal){ month = monthVal; day = dayVal;}public DayOfYear(int month){ this.month = month; day = 1;}public void input(){}public void output(){}private int month, day;

}

Very similar to C++, you can have multiple overloaded constructors

no argument constructor

overloaded constructor

Page 26: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Alternative Way to Initialize Instance Variables

You can initialize instance variables when you declare them in a class definition as follows

This is much different from C++!

Page 27: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Exercise

YourClass anObject = new YourClass(42, 'A'); YourClass anotherObject = new YourClass(41.99, 'A'); YourClass yetAnotherObject = new YourClass(); yetAnotherObject.doStuff();YourClass oneMoreObject; oneMoreObject.doStuff();oneMoreObject.YourClass(99, 'B');

public class YourClass { private int information; private char moreInformation; public YourClass( int newInfo, char moreNewInfo) { <Details not shown.> } public YourClass() {<Details not shown.> } public void doStuff() { <Details not shown.> } }

Given the following definition

Which of the following are legal?

Page 28: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Exercise

YourClass anObject = new YourClass(42, 'A'); YourClass anotherObject = new YourClass(41.99, 'A'); YourClass yetAnotherObject = new YourClass(); yetAnotherObject.doStuff();YourClass oneMoreObject; oneMoreObject.doStuff();oneMoreObject.YourClass(99, 'B');

public class YourClass { private int information; private char moreInformation; public YourClass( int newInfo, char moreNewInfo) { <Details not shown.> } public YourClass() {<Details not shown.> } public void doStuff() { <Details not shown.> } }

Given the following definition

Which of the following are legal?

Page 29: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Access Members

public class DayOfYearDemo{

public void main(){ DayOfYear date1, date2; //declaration date1 = new DayofYear(); //creates an object date2 = new DayofYear(2, 25); …… date1.month = 3; date1.day = 1; date1.output(); date2.output();}

}

Any problems of this code?

Using dot operator ‘.’ to access members of an object.

public class DayOfYear{…public void output{}private int month, day;}

Page 30: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Access Members

public class DayOfYearDemo{

public void main(){ DayOfYear date1, date2; //declaration date1 = new DayofYear(); //creates an object date2 = new DayofYear(2, 25); …… date1.month = 3; //illegal date1.day = 1; //illegal date1.output(); //legal date2.output(); //legal}

}

Any problems of this code?

Using dot operator ‘.’ to access members of an object.

public class DayOfYear{…public void output{}private int month, day;}

Page 31: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Access Members

public class DayOfYearDemo{

public void main(){ DayOfYear date1, date2; //declaration date1 = new DayofYear(); //creates an object date2 = new DayofYear(2, 25); …… date1.month = 3; //illegal date1.day = 1; //illegal date1.output(); //legal date2.output(); //legal}

}

How to fix it?

public class DayOfYear{…public void output{}private int month, day;}

Page 32: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Access Members

public class DayOfYearDemo{

public void main(){ DayOfYear date1, date2; //declaration date1 = new DayofYear(); //creates an object date2 = new DayofYear(2, 25); …… date1.month = 3; //illegal date1.day = 1; //illegal date1.output(); //legal date2.output(); //legal}

}

How to fix it?

Use accessor and mutators to access and modify the private member variables!

Page 33: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

public class ABC { private int information = 0; char moreInformation = ‘ ‘; public ABC ( int newInfo, char moreNewInfo) { <Details not shown.> } public ABC () {} public void update(int info, char moreInfo) { information = info; moreInformation = moreInfo; } void output_info() { System.out.println(“information=” + information + “, moreInformation=“ + moreInformation); } public ~ABC(){}};

public class Test{

public void main(){

ABC obj1 = new ABC (42, 'A'); ABC obj2;obj1.update (45, ‘A’);obj2.update (32, ‘B’);obj1.output_info();System.out.println(“information” + obj2.information + “, moreInformation=” + obj2.moreInformation);

}};

Page 34: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

public class ABC { private int information = 0; char moreInformation = ‘ ‘; public ABC ( int newInfo, char moreNewInfo) { <Details not shown.> } public ABC () {} public void update(int info, char moreInfo) { information = info; moreInformation = moreInfo; } void output_info() { System.out.println(“information=” + information + “, moreInformation=“ + moreInformation); } public ~ABC(){}};

public class Test{

public void main(){

ABC obj1 = new ABC (42, 'A'); ABC obj2;obj1.update (45, ‘A’);obj2.update (32, ‘B’);obj1.output_info();System.out.println(“information” + obj2.information + “, moreInformation=” + obj2.moreInformation);

}};

Page 35: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

public class ABC { private int information = 0; private char moreInformation = ‘ ‘; public ABC ( int newInfo, char moreNewInfo) { <Details not shown.> } public ABC () {} public void update(int info, char moreInfo) { information = info; moreInformation = moreInfo; } public void output_info() { System.out.println(“information=” + information + “, moreInformation=“ + moreInformation); }}

public class Test{

public void main(){

ABC obj1 = new ABC (42, 'A'); ABC obj2 = new ABC((int) 32.99, ‘B'); obj1.update (45, ‘A’);obj2.update (32, ‘B’);obj1.output_info();obj2.output_info();

}}

What is the output?

Page 36: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

public class ABC { private int information = 0; private char moreInformation = ‘ ‘; public ABC ( int newInfo, char moreNewInfo) { <Details not shown.> } public ABC () {} public void update(int info, char moreInfo) { information = info; moreInformation = moreInfo; } public void output_info() { System.out.println(“information=” + information + “, moreInformation=“ + moreInformation); }}

public class Test{

public void main(){

ABC obj1 = new ABC (42, 'A'); ABC obj2 = new ABC((int) 32.99, ‘B'); obj1.update (45, ‘A’);obj2.update (32, ‘B’);obj1.output_info();obj2.output_info();

}}

What is the output?

information=45, moreInformation=Ainformation=32, moreInformation=B

Page 37: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

public class ABC { private int information = 0; private char moreInformation = ‘ ‘; public ABC ( int newInfo, char moreNewInfo) { <Details not shown.> } public ABC () {} public void update(int info, char moreInfo) { information = info; moreInformation = moreInfo; } public void output_info() { System.out.println(“information=” + information + “, moreInformation=“ + moreInformation); }}

public class Test{

public void main(){

ABC obj1 = new ABC (42, 'A'); ABC obj2 = new ABC ((int) 32.99, ‘B'); obj1.update (45, ‘A’);obj2.update (32, ‘B’);obj2 = obj1;obj1.output_info();obj2.output_info();

}}

What is the output?

Page 38: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

public class ABC { private int information = 0; private char moreInformation = ‘ ‘; public ABC ( int newInfo, char moreNewInfo) { <Details not shown.> } public ABC () {} public void update(int info, char moreInfo) { information = info; moreInformation = moreInfo; } public void output_info() { System.out.println(“information=” + information + “, moreInformation=“ + moreInformation); }}

public class Test{

public void main(){

ABC obj1 = new ABC (42, 'A'); ABC obj2 = new ABC ((int) 32.99, ‘B'); obj1.update (45, ‘A’);obj2.update (32, ‘B’);obj2 = obj1;obj1.output_info();obj2.output_info();

}}

What is the output?

information=45, moreInformation=Ainformation=45, moreInformation=A

Page 39: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

public class ABC { private int information = 0; private char moreInformation = ‘ ‘; public ABC ( int newInfo, char moreNewInfo) { <Details not shown.> } public ABC () {} public void update(int info, char moreInfo) { information = info; moreInformation = moreInfo; } public void output_info() { System.out.println(“information=” + information + “, moreInformation=“ + moreInformation); }}

public class Test{

public void main(){

ABC obj1 = new ABC (42, 'A'); ABC obj2 = new ABC ((int) 32.99, ‘B'); obj1.update (45, ‘A’);obj2 = new ABC(32, ‘B’);obj1.output_info();obj2.output_info();

}}

What is the output?

Page 40: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

public class ABC { private int information = 0; private char moreInformation = ‘ ‘; public ABC ( int newInfo, char moreNewInfo) { <Details not shown.> } public ABC () {} public void update(int info, char moreInfo) { information = info; moreInformation = moreInfo; } public void output_info() { System.out.println(“information=” + information + “, moreInformation=“ + moreInformation); }}

public class Test{

public void main(){

ABC obj1 = new ABC (42, 'A'); ABC obj2 = new ABC ((int) 32.99, ‘B'); obj1.update (45, ‘A’);obj2 = new ABC(32, ‘B’);obj1.output_info();obj2.output_info();

}}

What is the output?

information=45, moreInformation=Ainformation=32, moreInformation=B

Page 41: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Static MembersStatic variables A static variable is a variable that belongs to the class as a

whole and not just to one object.

Still defined in a class!

If you do not initialize a static variable, it is automatically initialized to a default value:

• boolean – false• int, float, double, char, short, long – zero• class type – null

private static int turn;

private static int turn = 0;or

Page 42: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Static MembersStatic methods In Java, you can define a method so that it requires no calling

object. Such methods are known as static methods.

Still defined in a class!

Let us assume the above static function is defined in a class named ‘ABC’, the way to invoke this static function is as follows

int budget = ABC.maximum (yourMoney, myMoney);

How did we do that in C++?

Page 43: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Static MembersStatic methods In Java, you can define a method so that it requires no calling

object. Such methods are known as static methods.

Still defined in a class!

Let us assume the above static function is defined in a class named ‘ABC’, the way to invoke this static function is as follows

int budget = ABC.maximum (yourMoney, myMoney);

You cannot invoke a non-static function within a static function! Why?

Page 44: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

The methods equals and toString

• Java expects certain methods, such as equals and toString, to be in all, or almost all, classes. – Guess where are they from?

• The purpose of equals, a boolean valued method, is to compare two objects of the class to see if they satisfy the notion of "being equal"– Note: You cannot use == to compare objects in Java public boolean equals(ClassName objectName)

Page 45: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

The methods equals and toString

• Java expects certain methods, such as equals and toString, to be in all, or almost all, classes. – Guess where are they from?

• The purpose of equals, a boolean valued method, is to compare two objects of the class to see if they satisfy the notion of "being equal"– Note: You cannot use == to compare objects in Java public boolean equals(ClassName objectName)

• The purpose of the toString method is to return a String value that represents the data in the object public String toString()- Guess what is that for?

Page 46: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Example

function overwriting!

Page 47: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Example (continued)

What does it output?

date1 and date2 are complicated type

Page 48: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Example (continued)

Page 49: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Does Java support operator overloading?

Page 50: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Does Java support operator overloading?

NO! It does not. You cannot overload the operator for your complex objects.

However, ‘+’ is overloaded for String type of objects.

Page 51: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Does Java support overloading functions at all?

Page 52: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Does Java support overloading functions at all?

Yes! We have seen the overloading constructors in the previous example!

Page 53: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable
Page 54: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

What is the signature of a method?

Page 55: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

What is the signature of a method?

method name + argument list

Page 56: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Are the following two overloading functions?

public void setDate (int year){ ……}

public boolean setDate (int month){ return true;}

Page 57: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Are the following two overloading functions?

public void setDate (int year){ ……}

public boolean setDate (int month){ return true;}

They are not!because they have exactly the same signature!

Page 58: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

public class Dog{ private char[20] = “";

public Dog (const char[20]) { <Details not shown> }

public static void main( String[] args ) { Dog aDog = new Dog("Max"); foo(aDog); if( aDog.getName().equals("Max") ) { System.out.println( "Java passes by value." ); } else if( aDog.getName().equals("Fifi") ) { System.out.println( "Java passes by reference." ); } }

public static void foo(Dog d) { d.getName().equals("Max"); d = new Dog("Fifi"); d.getName().equals("Fifi"); }}

What is the output?

Page 59: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

public class Dog{ private char[20] = “";

public Dog (const char[20]) { <Details not shown> }

public static void main( String[] args ) { Dog aDog = new Dog("Max"); foo(aDog); if( aDog.getName().equals("Max") ) { System.out.println( "Java passes by value." ); } else if( aDog.getName().equals("Fifi") ) { System.out.println( "Java passes by reference." ); } }

public static void foo(Dog d) { d.getName().equals("Max"); d = new Dog("Fifi"); d.getName().equals("Fifi"); }}

What is the output?

Java passes by value.

Why?

Page 60: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Java Inheritance

Page 61: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

What do we know already?• Inheritance is one of the main techniques of object-

oriented programming (OOP).• It enables potentially infinite reuse of resources.• It can be used to enhance and improve the previous

programs for the changing requirements

Page 62: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

What do we know already?• Inheritance is one of the main techniques of object-

oriented programming (OOP).• It enables potentially infinite reuse of resources.• It can be used to enhance and improve the previous

programs for the changing requirements

In one sentence, inheritance allows us to create new classes from the existing classes without doing much repeated work.

Page 63: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Java InheritanceHow did we do that in C++

#include <string>using std::string;

class Employee{public: // constructor list // member functionsprivate: string name, ssn; double netPay;};

class HourlyEmployee : public Employee{public: // constructor list // new member functionsprivate: double wageRate; double hours;};

Page 64: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Java InheritanceHow did we do that in C++

#include <string>using std::string;

class Employee{public: // constructor list // member functionsprivate: string name, ssn; double netPay;};

class HourlyEmployee : public Employee{public: // constructor list // new member functionsprivate: double wageRate; double hours;};

base/parent/super- class

derived/child/sub- class

Page 65: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Java InheritanceHow did we do that in C++

#include <string>using std::string;

class Employee{public: // constructor list // member functionsprivate: string name, ssn; double netPay;};

class HourlyEmployee : public Employee{public: // constructor list // new member functionsprivate: double wageRate; double hours;};

How should we do that in java?

public class Employee{public // constructor listpublic // member functionsprivate: string name, ssn; double netPay;};

what is wrong with the above code?

Page 66: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Java InheritanceHow did we do that in C++

#include <string>using std::string;

class Employee{public: // constructor list // member functionsprivate: string name, ssn; double netPay;};

class HourlyEmployee : public Employee{public: // constructor list // new member functionsprivate: double wageRate; double hours;};

How should we do that in java?

public class Employee{public // constructor listpublic // member functionsprivate string name, ssn;private double netPay;}

Page 67: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Java InheritanceHow did we do that in C++

#include <string>using std::string;

class Employee{public: // constructor list // member functionsprivate: string name, ssn; double netPay;};

class HourlyEmployee : public Employee{public: // constructor list // new member functionsprivate: double wageRate; double hours;};

How should we do that in java?

public class Employee{public // constructor listpublic // member functionsprivate string name, ssn;private double netPay;}

public class HourlyEmployee extends Employee{public // constructor list // new member functionsprivate double wageRate;private double hours;}

Page 68: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Java Inheritance

• The phrase extends BaseClass must be added to the derived class definition.

• The derived class inherits all the public methods, all the public and private instance variables, and all the public and private static variables from the base class.• The code is reused without having to explicitly copy it, unless the

creator of the derived class redefines one or more of the base class methods

• The derived class can add more instance variables, static variables, and/or methods

Page 69: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Overriding a methodWe know that the derived class can modify the definition of certain methods that are inherited from the base class. This mechanism is called method overriding or redefinition.

How to achieve that?

Page 70: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Overriding a methodWe know that the derived class can modify the definition of certain methods that are inherited from the base class. This mechanism is called method overriding or redefinition.

in C++?

class Base{public: void print() { cout << “I am a base object. \n”; }private: int val1; string val2;};

class Derived : public Base{public: void print() { cout << “I am a derived object. \n”; }private: int val3; double val4;};

Need to have exactly the same signature!

Page 71: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Overriding a methodWe know that the derived class can modify the definition of certain methods that are inherited from the base class. This mechanism is called method overriding or redefinition.

in Java?

public class Base{public void print(){ System.out.println(“I am a base object.”);}private int val1;private string val2;}

public class Derived extends Base{public void print(){ System.out.println(“I am a derived object.”);}private int val3;private double val4;}

Need to have exactly the same signature!

Page 72: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Overriding a methodWe know that the derived class can modify the definition of certain methods that are inherited from the base class. This mechanism is called method overriding or redefinition.

in Java?

Need to have exactly the same signature!

Do you still remember the difference from the function overloading?

public class Base{public void print(){ System.out.println(“I am a base object.”);}private int val1;private string val2;}

public class Derived extends Base{public void print(){ System.out.println(“I am a derived object.”);}private int val3;private double val4;}

Page 73: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Overriding a methodCan the return type of the overriding method be modified?

public class Base{public void print(){ System.out.println(“I am a base object.”);}private int val1;private string val2;}

public class Derived extends Base{public boolean print(){ System.out.println(“I am a derived object.”); return true;}private int val3;private double val4;}

Page 74: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Overriding a methodCan the return type of the overriding method be modified?

No!

public class Base{public void print(){ System.out.println(“I am a base object.”);}private int val1;private string val2;}

public class Derived extends Base{public boolean print(){ System.out.println(“I am a derived object.”); return true;}private int val3;private double val4;}

Page 75: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Overriding a methodCan the return type of the overriding method be modified?

public class Base{public Employee func(){ … return Employee();}private int val1;private string val2;}

public class Derived extends Base{public HourlyEmployee func(){……return HourlyEmployee();}private int val3;private double val4;}

But if the return type is a class type, the following is allowed

Note that the overriding method in the derived class has the return type which is the derived class of the return type of the original function!

This is known as a covariant return type.

Page 76: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Overriding a methodCan we change the access modifier of a method?

public class Base{private void print(){ System.out.println(“I am a base object.”);}private int val1;private string val2;}

public class Derived extends Base{public void print(){ System.out.println(“I am a derived object.”);}private int val3;private double val4;}

Page 77: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Overriding a methodCan we change the modifier of a method?

Yes!

public class Base{private void print(){ System.out.println(“I am a base object.”);}private int val1;private string val2;}

public class Derived extends Base{public void print(){ System.out.println(“I am a derived object.”);}private int val3;private double val4;}

Page 78: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Overriding a methodCan we change the modifier of a method?

Yes!

• The access permission of an overridden method can be changed from private in the base class to public (or some other more permissive access) in the derived class.

• However, the access permission of an overridden method cannot be changed from public in the base class to a more restricted access permission in the derived class

public class Base{private void print(){ System.out.println(“I am a base object.”);}private int val1;private string val2;}

public class Derived extends Base{public void print(){ System.out.println(“I am a derived object.”);}private int val3;private double val4;}

Page 79: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

The final Modifier

• If the modifier final is placed before the definition of a method, then that method may not be redefined (or overridden) in a derived class

• If the modifier final is placed before the definition of a class, then that class may not be used as a base class to derive other classes

Page 80: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

public class Base{public final void print(){ System.out.println(“I am a base object.”);}private int val1;private string val2;}

public class Derived extends Base{public void print() //illegal! Not allowed{ System.out.println(“I am a derived object.”);}private int val3;private double val4;}

final public class Base{……}

public class Derived extends Base //illegal{……}

Page 81: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Hide member variablesDerived class can have the variables with the same names as those inherited from the base class, but this is NOT a redefinition. It is simply hiding the variables from the base class!

public class Base{private void print(){ cout << “I am a base object. \n”;}public int val1;private string val2;}

public class Derived extends Base{public void print(){ cout << “I am a derived object. \n”; return true;}public int val1;private double val4;}

public class TestClass{

public void main (String[] arg){Derived obj = new Derived();obj.val1 = 1; // this is the variable //in the derived class}

}

Page 82: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Hide member variables

public class Dad { protected static String me = "dad"; public void printMe() { System.out.println(me); } }

class Son extends Dad { protected static String me = "son"; }

class Tester { public static void main(String[] arg) { new Son().printMe(); } }

What will be the output of this code?

Page 83: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Hide member variables

public class Dad { protected static String me = "dad"; public void printMe() { System.out.println(me); } }

class Son extends Dad { protected static String me = "son"; public void printMe() { System.out.println(me); } }

class Tester { public static void main(String[] arg) { new Son().printMe(); } }

Now, what will be the output?

Page 84: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Constructor of the derived class

This is what we did in C++

class DerivedClass : public BaseClass{…public:

DerivedClass (argument list) : BaseClass (argument list), A (initial value)

{}

…private: A obj; //A is a pre-defined class!};

base class - > composite objects -> other variables in the derived class

Page 85: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Constructor of the derived classIn Java, we also need to take care of the initialization of the variables inherited from the base class.But how should we do that?

Page 86: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Constructor of the derived classIn Java, we also need to take care of the initialization of the variables inherited from the base class.But how should we do that?

It uses a so-called “super” constructor to initialize the inherited variables.

public class Base{public Base(){ val1= 0; val2 = “”;}public int val1;private string val2;}

public class Derived extends Base{public Derived(){ super(); val1 = 0; val4 = 0.0;}public int val1;private double val4;}

will call the base constructor!

Page 87: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

The super Constructor

• A call to the base class constructor can never use the name of the base class, but uses the keyword super instead

• A call to super must always be the first action taken in a constructor definition

Page 88: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

The super Constructor

• If a derived class constructor does not include an invocation of super, then the no-argument constructor of the base class will automatically be invoked– This can result in an error if the base class has not defined

a no-argument constructor

• Since the inherited instance variables should be initialized, and the base class constructor is designed to do that, then an explicit call to super should always be used

Page 89: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

More examples on super constructorpublic class Employee{ private String name; private Date hireDate; // Date is a previously defined class

public Employee( ) { name = "No name"; hireDate = new Date("Jan", 1, 1000); //Just a placeholder. }

/** Precondition: Neither theName nor theDate is null. */ public Employee(String theName, Date theDate) { if (theName == null || theDate == null) { System.out.println("Fatal Error creating employee."); System.exit(0); } name = theName; hireDate = new Date(theDate); }

public Employee(Employee originalObject) // copy constructor! { name = originalObject.name; hireDate = new Date(originalObject.hireDate); }……}

The base class

Page 90: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

More examples on super constructorpublic class HourlyEmployee extends Employee { private double wageRate; private double hours; //for the month public HourlyEmployee( ) { super( ); wageRate = 0; hours = 0; } public HourlyEmployee(String theName, Date theDate, double theWageRate, double theHours) { super(theName, theDate); if ((theWageRate >= 0) && (theHours >= 0)) { wageRate = theWageRate; hours = theHours; } else { System.out.println( "Fatal Error: creating an illegal hourly employee."); System.exit(0); } } public HourlyEmployee(HourlyEmployee originalObject) { super(originalObject); // Why this is legal? wageRate = originalObject.wageRate; hours = originalObject.hours; }……}

A derived class

Page 91: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

More examples on super constructorpublic class Base{

private int x, y = 0;public Base(int x_val, int y_val){ x = x_val; y = y_val;}public Base(int x_val){ x = x_val; }……

}

The base class

public class Derived extends Base{

private double x, y = 0;public Derived(double x_val, double y_val){ x = x_val; y = y_val;}public Derived(double x_val){ x = x_val; super (x_val);}……

}

The derived class

What is the problem in the derived class?

Page 92: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

More examples on super constructorpublic class Base{

private int x, y = 0;public Base(int x_val, int y_val){ x = x_val; y = y_val;}public Base(int x_val){ x = x_val; }……

}

The base class

public class Derived extends Base{

private double x, y = 0;public Derived(double x_val, double y_val){ x = x_val; y = y_val; //Base class does not have no-argument //constructor}public Derived(double x_val){ x = x_val; super ((int)x_val); //should be the first line, and…}……

}

The derived class

Page 93: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

The this Constructor• Within the definition of a constructor for a class, this can be used as a

name for invoking another constructor in the same class (not the base class!)– this cannot be invoked by an instance variable

• Often, a no-argument constructor uses this to invoke an explicit-value constructor– No-argument constructor (invokes explicit-value constructor using this and default arguments):

public ClassName(){ this(argument1, argument2);}

– Explicit-value constructor (receives default values):public ClassName(type1 param1, type2 param2){ . . .}

Page 94: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Examplepublic HourlyEmployee(){ this("No name", new Date(), 0, 0);}

• The above constructor will cause the constructor with the following heading to be invoked:public HourlyEmployee(String theName, Date theDate, double theWageRate, double theHours)

Page 95: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

The this Constructor

• If it is necessary to include a call to both super and this, the call using this must be made first, and then the constructor that is called must call super as its first action

Page 96: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Examplepublic class Base{

private int x, y = 0;public Base(int x_val, int y_val){ x = x_val; y = y_val;}public Base(int x_val){ x = x_val; }……

}

public class Derived extends Base{

private double x, y = 0;public Derived(){ this (0.0, 1.0);}public Derived(double x_val, double y_val){ super ((int)x_val, (int)y_val); // x = x_val; y = y_val;}……

}

The base class

The derived class

Page 97: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Examplepublic class Base{

int x, y = 0;public Base(int x_val, int y_val){ x = x_val; y = y_val; System.out.println(“Base class.”);}public Base(){ this (0, 0); }……

}

public class Derived extends Base{

public double x, y = 0;public Derived(){ this (0.0, 1.0);}public Derived(double x_val, double y_val){ super ((int)x_val, (int)y_val); x = x_val; y = y_val; System.out.println(“Derived class.”);}……

}

public class Try{

public static void main(String[] args){ Base b_obj = new Base(); Derived d_obj = new Derived(); print(b_obj); print(d_obj);}public static void print(Base obj){System.out.println(“x=“+obj.x);System.out.println(“y=“+obj.y);}

}

What will be the output?

Page 98: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Examplepublic class Base{

int x, y = 0;public Base(int x_val, int y_val){ x = x_val; y = y_val; System.out.println(“Base class.”);}public Base(){ this (0, 0); }……

}

public class Derived extends Base{

private double x, y = 0;public Derived(){ this (0.0, 1.0);}public Derived(double x_val, double y_val){ super ((int)x_val, (int)y_val); x = x_val; y = y_val; System.out.println(“Derived class.”);}……

}

Base class.Base class.Derived class.x=0y=0x=0y=1

public class Try{

public static void main(String[] args){ Base b_obj = new Base(); Derived d_obj = new Derived(); print(b_obj); print(d_obj);}public static void print(Base obj){System.out.println(“x=“+obj.x);System.out.println(“y=“+obj.y);}

}

Page 99: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Going back to overriding methodsHow can you access the method in the base class?

public class Student{public void getInfo(){ ……}private String name;private string ID;}

public class GradStudent extends Student{public void getInfo(){ // how can I invoke the getInfo in the base}private float score;private char degree;}

Page 100: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Going back to overriding methodsHow can you access the method in the base class?

public class Student{public void getInfo(){ ……}private String name;private string ID;}

public class GradStudent extends Student{public void getInfo(){ super.getInfo(); ……}private float score;private char degree;}

Use super!

but can we use super.super.func() to invoke the function in ancestor class?

Page 101: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Protected and Package Access

• If a method or instance variable is modified by protected (rather than public or private), then it can be accessed by name– Inside its own class definition – Inside any class derived from it– In the definition of any class in the same package

• The protected modifier provides very weak protection compared to the private modifier– It allows direct access to any programmer who defines a suitable

derived class– Therefore, instance variables should normally not be marked protected

Page 102: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Protected and Package Access

• An instance variable or method definition that is not preceded with a modifier has package access– Package access is also known as default or friendly access

• Instance variables or methods having package access can be accessed by name inside the definition of any class in the same package– However, neither can be accessed outside the package

Page 103: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Protected and Package Access

• Note that package access is more restricted than protected– Package access gives more control to the

programmer defining the classes– Whoever controls the package directory (or

folder) controls the package access

Page 104: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Access Modifiers

Page 105: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Examplepackage one;public class B{ protected int n; ...}

which ones the following are legal?

package two;import one.B;public class D extends B{...}

public class D extends B{public void demo(){ n = 42;}}

public class D extends B{public void demo3(){ B object = new B(); object.n = 42;}}

public class D extends B{public void demo2(){ D object = new D(); object.n = 42;}}

Page 106: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

Examplepackage one;public class B{ protected int n; ...}

which ones the following are legal?

package two;import one.B;public class D extends B{...}

public class D extends B{public void demo(){ n = 42;}}

public class D extends B{public void demo3(){ B object = new B(); object.n = 42;}}

public class D extends B{public void demo2(){ D object = new D(); object.n = 42;}}

legal illegallegal

Page 107: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

“Is a” versus “Has a”

What is the difference between this two relations in real world?Can you provide one or two examples for these relations?

Page 108: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

“Is a” versus “Has a”

What is the difference between this two relations in real world?Can you provide one or two examples for these relations?

Human is a primatePrimate is a mammal……

Technician is a fixed-wage employeefixed-wage employee is an employee……

Examples of “Is a” relation:

Circle is a 2D shape2D shape is a shape……

Page 109: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

“Is a” versus “Has a”

What is the difference between this two relations in real world?Can you provide one or two examples for these relations?

Human is a primatePrimate is a mammal……

Technician is a fixed-wage employeefixed-wage employee is an employee……

Examples of “Is a” relation:

Circle is a 2D shape2D shape is a shape……

Clearly, inheritance demonstrates the “is a” relation between objects

Page 110: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

“Is a” versus “Has a”

What is the difference between this two relations in real world?Can you provide one or two examples for these relations?

So what about “has a” relation?

Page 111: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

“Is a” versus “Has a”

What is the difference between this two relations in real world?Can you provide one or two examples for these relations?

So what about “has a” relation?

Indeed, it links to the concept of “object composition”.

Page 112: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

“Is a” versus “Has a”

What is the difference between this two relations in real world?Can you provide one or two examples for these relations?

So what about “has a” relation?

Indeed, it links to the concept of “object composition”.X is part of a bigger object Y.

Page 113: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

“Is a” versus “Has a”

What is the difference between this two relations in real world?Can you provide one or two examples for these relations?

So what about “has a” relation?

Indeed, it links to the concept of “object composition”.X is part of a bigger object Y.

In OOP language, X is the member variable of Y.

public class Comp1{……}

public class Container{private Comp1 cp;……}

Page 114: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

The Class Object

• In Java, every class is a descendent of the class Object– Every class has Object as its ancestor– Every object of every class is of type Object, as well as being of the

type of its own class

• If a class is defined that is not explicitly a derived class of another class, it is still automatically a derived class of the class Object

• Object is the root of all classes in Java!

Page 115: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

The Class Object• Location: The class Object is in the package java.lang

which is always imported automatically

• Benefit 1: The class Object has some methods that every Java class inherits– For example, the equals and toString methods

– However, these inherited methods should be overridden with definitions more appropriate to a given class

Page 116: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

The Class Object• Benefit 2: Having an Object class enables methods

to be written with a parameter of type Object– A parameter of type Object can be replaced by an object

of any class whatsoever– For example, some library methods accept an argument

of type Object so they can be used with an argument that is an object of any class

public class Demoprog{ public void func (Object input_obj) { …… }}

Can be used for other class types!

Page 117: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

getClass() method

Every object inherits the method getClass()from the class Object . The method getClass()is marked final in the class Object , so it cannot be overridden.

For any object obj, obj.getClass() returns a representation of the class used to create obj.

If Object obj = new Employee();

Then obj.getClass() return a representation Employee

Page 118: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

getClass() methodUse getClass() method to achieve a better implementation of the equals (Object in_obj) overriding

Recall that we need to override/redefine this function inherited from the Object class

Page 119: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

instanceof Operator

Object instanceof Class_Name

This will return true if Object is of type Class_Name

Object obj = new Employee();……(obj instanceof Employee) true

Page 120: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

instanceof Operator

Object instanceof Class_Name

This will return true if Object is of type Class_Name

Object obj = new HourlyEmployee();……(obj instanceof Employee)

How about this?

Page 121: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

instanceof Operator

Object instanceof Class_Name

This will return true if Object is of type Class_Name

Object obj = new HourlyEmployee();……(obj instanceof Employee) true as well!

So what is it different from the use of the getClass() method?

Page 122: Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable

e.equals(hourlyE)?hourlyE.equals(e)?