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

Post on 23-Dec-2015

220 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

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 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.)

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.*

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

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

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!

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>)

{ ……}

}

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.

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! ……}

Class in Java

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

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

How to define a class in Java?

How did we do that in C++?

How to define a class in Java?

How did we do that in C++?

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

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?

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!

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?

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;}

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;}

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

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

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.

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!

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!

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

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++!

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?

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?

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;}

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;}

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;}

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!

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);

}};

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);

}};

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?

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

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?

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

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?

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

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

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++?

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?

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 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?

Example

function overwriting!

Example (continued)

What does it output?

date1 and date2 are complicated type

Example (continued)

Does Java support operator overloading?

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.

Does Java support overloading functions at all?

Does Java support overloading functions at all?

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

What is the signature of a method?

What is the signature of a method?

method name + argument list

Are the following two overloading functions?

public void setDate (int year){ ……}

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

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!

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?

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?

Java Inheritance

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

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.

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;};

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

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?

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;}

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;}

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

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?

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!

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!

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;}

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;}

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;}

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.

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;}

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;}

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;}

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

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{……}

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}

}

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?

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?

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

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?

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!

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

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

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

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

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?

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

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){ . . .}

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)

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

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

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?

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);}

}

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;}

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?

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

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

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

Access Modifiers

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;}}

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

“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?

“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……

“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

“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?

“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”.

“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.

“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;……}

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!

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

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!

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

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

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

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?

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?

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

top related