Presentation is loading. Please wait.

Presentation is loading. Please wait.

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 presentations


Presentation on theme: "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."— Presentation transcript:

1 Some Quick Reviews of Java

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

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

4 Java and C/C++ Screen I/O streams #include printf(“ ”, var1, var2…); scanf(“ ”, &var1, &var2…); C java System.out.printf(“ ”, var1, var2,…); System.out.print(String…); //in same line System.out.println(String…); //next line import java.util.Scanner //for input Scanner keyboard = new Scanner(System.in); int var1 = keyboard.nextInt(); double var2 = keyboard.nextDouble(); String s1 = keyboard.next(); // read one word String s2 = keyboard.nextline(); //read one line C++ #include cout << endl; cin >> variable

5 Java and C/C++ What are similar or same Basic types, e.g. int, float, double, char, … automatic type conversion byte  short  int  long  float  double 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

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

7 Java and C/C++ execution entrance #include void main ( ) { …… } C/C++ java import package.class … public class class_name /* must have the same name as the file*/ { public static void main( ) { …… }

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

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

10 Class in Java

11 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

12 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

13 How to define a class in Java? How did we do that in C++?

14 How to define a class in Java? How did we do that in C++? class class_name { public: //member func. … private: // attribute list };

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

16 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 func1 public member func2 … private member var1 private member var2 … } No semi-column!

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

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

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

20 class in java public 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

21 class in java public 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

22 class in java public 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.

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

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

25 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

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

27 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) { } public YourClass() { } public void doStuff() { } } Given the following definition Which of the following are legal?

28 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) { } public YourClass() { } public void doStuff() { } } Given the following definition Which of the following are legal?

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

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

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

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

33 public class ABC { private int information = 0; char moreInformation = ‘ ‘; public ABC ( int newInfo, char moreNewInfo) { } 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); } };

34 public class ABC { private int information = 0; char moreInformation = ‘ ‘; public ABC ( int newInfo, char moreNewInfo) { } 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); } };

35 public class ABC { private int information = 0; private char moreInformation = ‘ ‘; public ABC ( int newInfo, char moreNewInfo) { } 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?

36 public class ABC { private int information = 0; private char moreInformation = ‘ ‘; public ABC ( int newInfo, char moreNewInfo) { } 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=A information=32, moreInformation=B

37 public class ABC { private int information = 0; private char moreInformation = ‘ ‘; public ABC ( int newInfo, char moreNewInfo) { } 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?

38 public class ABC { private int information = 0; private char moreInformation = ‘ ‘; public ABC ( int newInfo, char moreNewInfo) { } 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=A

39 public class ABC { private int information = 0; private char moreInformation = ‘ ‘; public ABC ( int newInfo, char moreNewInfo) { } 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?

40 public class ABC { private int information = 0; private char moreInformation = ‘ ‘; public ABC ( int newInfo, char moreNewInfo) { } 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=A information=32, moreInformation=B

41 Static Members Static variablesA 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

42 Static Members Static methodsIn 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++?

43 Static Members Static methodsIn 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?

44 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" You cannot use == to compare objects in Java – Note: You cannot use == to compare objects in Java public boolean equals(ClassName objectName)

45 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" You cannot use == to compare objects in Java – 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?

46 Example function overwriting!

47 Example (continued) What does it output? date1 and date2 are complicated type

48 Example (continued)

49 Does Java support operator overloading?

50 NO! It does not. You cannot overload the operator for your complex objects. However, ‘+’ is overloaded for String type of objects.

51 Does Java support overloading functions at all?

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

53

54 What is the signature of a method?

55 method name + argument list

56 Are the following two overloading functions? public void setDate (int year) { …… } public boolean setDate (int month) { return true; }

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

58 public class Dog{ private char[20] = “"; public Dog (const char[20]) { } 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?

59 public class Dog{ private char[20] = “"; public Dog (const char[20]) { } 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?

60 Java Inheritance

61 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

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

63 Java Inheritance How did we do that in C++ #include using std::string; class Employee { public: // constructor list // member functions private: string name, ssn; double netPay; }; class HourlyEmployee : public Employee { public: // constructor list // new member functions private: double wageRate; double hours; };

64 Java Inheritance How did we do that in C++ #include using std::string; class Employee { public: // constructor list // member functions private: string name, ssn; double netPay; }; class HourlyEmployee : public Employee { public: // constructor list // new member functions private: double wageRate; double hours; }; base/parent/super- class derived/child/sub- class

65 Java Inheritance How did we do that in C++ #include using std::string; class Employee { public: // constructor list // member functions private: string name, ssn; double netPay; }; class HourlyEmployee : public Employee { public: // constructor list // new member functions private: double wageRate; double hours; }; How should we do that in java? public class Employee { public // constructor list public // member functions private: string name, ssn; double netPay; }; what is wrong with the above code?

66 Java Inheritance How did we do that in C++ #include using std::string; class Employee { public: // constructor list // member functions private: string name, ssn; double netPay; }; class HourlyEmployee : public Employee { public: // constructor list // new member functions private: double wageRate; double hours; }; How should we do that in java? public class Employee { public // constructor list public // member functions private string name, ssn; private double netPay; }

67 Java Inheritance How did we do that in C++ #include using std::string; class Employee { public: // constructor list // member functions private: string name, ssn; double netPay; }; class HourlyEmployee : public Employee { public: // constructor list // new member functions private: double wageRate; double hours; }; How should we do that in java? public class Employee { public // constructor list public // member functions private string name, ssn; private double netPay; } public class HourlyEmployee extends Employee { public // constructor list // new member functions private double wageRate; private double hours; }

68 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

69 Overriding a method We 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?

70 Overriding a method We 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!

71 Overriding a method We 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!

72 Overriding a method We 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; }

73 Overriding a method Can 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; }

74 Overriding a method Can 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; }

75 Overriding a method Can 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.

76 Overriding a method Can 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; }

77 Overriding a method Can 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; }

78 Overriding a method Can 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; }

79 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

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

81 Hide member variables Derived 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 }

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

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

84 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

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

86 Constructor of the derived class In 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!

87 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

88 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

89 More examples on super constructor public 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

90 More examples on super constructor public 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

91 More examples on super constructor public 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?

92 More examples on super constructor public 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

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

94 Example public 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)

95 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

96 Example public 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

97 Example public 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?

98 Example public 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. Derived class. x=0 y=0 x=0 y=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); }

99 Going back to overriding methods How 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; }

100 Going back to overriding methods How 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?

101 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

102 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

103 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

104 Access Modifiers

105 Example package 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; }

106 Example package 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

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

108 “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 primate Primate is a mammal …… Technician is a fixed-wage employee fixed-wage employee is an employee …… Examples of “Is a” relation: Circle is a 2D shape 2D shape is a shape ……

109 “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 primate Primate is a mammal …… Technician is a fixed-wage employee fixed-wage employee is an employee …… Examples of “Is a” relation: Circle is a 2D shape 2D shape is a shape …… Clearly, inheritance demonstrates the “is a” relation between objects

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

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

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

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

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

115 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

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

117 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

118 getClass() method Use 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

119 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

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

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

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


Download ppt "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 presentations


Ads by Google