Chapter 6: Taking a look at the Java Class Features.

(6 hrs) Chapter Objectives: – Distinguish the rules of inheritance and Polymorphism in Java. – Decide when to use the default (package-friendly) and protected access modifiers. – Explain when to use overloading and overriding – Explain the importance of Virtual Method Invocation and how it can be used in having Polymorphic Arguments – Describe the use of the instanceof operator. – Decide the scenarios when to cast objects. – Show how to use the tiger's varargs capability – Recommend the different way on how to use a class' constructor and method overloading. – Explain how constructors in Java are chained. – State the use of the super keyword. – Investigate the Object class as well as the equals() and toString() methods. – List the importance of the Wrapper Classes. – Use the auto box-in and auto box-out capability. Inheritance Inheritance is another fundamental concept of object-oriented programming. The idea behind inheritance is that you can create new classes that are built on existing classes. When you inherit from an existing class, you reuse (or inherit) its methods and fields and you add new methods and fields to adapt your new class to new situations. This technique is essential in Java programming. If you are coming from a procedure-oriented language like C, Visual Basic, or COBOL, you will want to read this chapter carefully. For experienced C++ programmers or those coming from another object-oriented language like Smalltalk, this chapter will seem largely familiar, but there are many differences between how inheritance is implemented in Java and how it is done in C++ or in other object-oriented languages. Classes, Superclasses, and Subclasses Let’s look at the Employee class.

public class public public public public }

Employee { String name = ""; double salary; Date birthDate; String getDetails() {...}

Suppose (alas) you work for a company at which managers are treated differently from other employees. Managers are, of course, just like employees in many respects. Both employees and managers are paid a salary.
Page 1 of 12 Prepared by: Lawrence G. Decamora III, scjp

Here is how you define a Manager class that inherits from the Employee class.. scjp . there is an obvious “is–a” relationship between Manager and Employee. double salary. Manager. and add functionality. managers are assigned to a particular department This is the kind of situation that cries out for inheritance. More abstractly. String getDetails() {. You use the Java keyword extends to denote inheritance.. class Manager extends Employee added methods and fields } { public class public public public public } Page 2 of 12 Employee { String name = "". you need to define a new class. double salary. Why? Well. String getDetails() {. while employees are expected to complete their assigned tasks in return for receiving their salary.} Prepared by: Lawrence G. Every manager is an employee: This “is–a” relationship is the hallmark of inheritance. Date birthDate.} However. and all the fields of the original class can be preserved. Decamora III. But you can retain some of what you have already programmed in the Employee class.public class public public public public public } Manager { String name = ""... Date birthDate. String department.

for example: A +doStuff() B +doStuff() C Here's a potential problem that can occur in multiple inheritance. Unlike in other programming languages. which means you can only inherit from a single superclass (parent class).public class Manager extends Employee { public String department. Interfaces will be discussed towards the end of module 7. like C++ in which multiple inheritance is allowed. Multiple inheritance has several drawbacks. Java is more organized and strongly typed. } Single Inheritance In the Java Programming Language. scjp . What if class A and class B has different implementation of the doStuff() method? Which one will be inherited and implemented by class C? But it doesn't stop there. This is NOT allowed in Java. Decamora III. in Java. we can only practice Single Inheritance. but in other programming languages like C++ is allowed. we can still simulated multiple inheritance by using interfaces. So. Page 3 of 12 Prepared by: Lawrence G. does it make Java weaker than C++? No.

the getDetails() method of the Manager class is overriding the getDetails() method of the Employee class. A subclass can modify the functionality of the inherited method with a different functionality than the parent's method but it must have the same name. Page 4 of 12 Prepared by: Lawrence G. However. public String getDetails() { return “Name: “ + name + “\nSalary: “ + salary. public String getDetails() { return “Name: “ + name + “\nSalary: “ + salary + “\nDepartment: ” + department.Java Access Modifiers Access Modifiers private <default> protected public Same Class     Same Package X    Subclass X X   Anywhere X X X  Method Overriding There are instances that when you inherit a method from a superclass. Decamora III. The super keyword is used in a class to refer to its super class' member data (attributes and methods). Thus. public double salary. we can use the super keyword. scjp . Also. you will see redundancy in lines 5 to 7 of the Employee class and lines 3 to 7 of the Manager class. the access modifier of the overriding method must not be less accessible. and same argument list. The super keyword To eliminate this problem. The behavior does not have to be in the immediate superclass. this is not a very elegant way to write this code. } } In this example. in the given example. It is because that the Manager's getDetails() method is suppose to give out more information than the inherited getDetails() method of the Employee class. 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 public class Employee { public String name = "". the method that you've inherited is not quite enough to perform the duties required by the subclass. you can override the method you've inherited. public Date birthDate. but for Java 5. it can be further up in the hierarchy. To resolve this issue.4 and below. } } public class Manager extends Employee { public String department. return type (for Java 1.0 and above the return type can be a subclass of the return type of the superclass' method).

In Java. However.println(e. Decamora III.. Page 5 of 12 Prepared by: Lawrence G.out.. The question is which getDetails() method will be implemented? The one in the Employee class or the one in the Manager class? Virtual Method Invocation To answer the question above. we need to know Java's way on handling overridden methods. the object itself is non polymorphic. 3 public double salary. 5 public String getDetails() { 6 return “Name: “ + name + 7 “\nSalary: “ + salary. which means variable e can be assigned to any Employee type object like Manager. public String getDetails() { return super. the department (or any called member) must be a member of the class type (in this case. } } In this new version. Here's an example of polymorphism: 5 Employee e = new Manager(). . scjp . Because all of these classes are a subclass of the Employee class.getDetails()). but the reference variable is. however the objects that resides on the heap memory are not polymorphic.getDetails() + “\nDepartment: ” + department. // this is ok! Line 5 is allowed because the reference variable e is a polymorphic variable. reference variables resides on the stack memory that's why they can be polymorphic. As we recall. polymorphism actually means having many changes or having many forms. Polymorphism Polymorphism was derived from two greek words.getDetails()).out. This is because there is no department attribute in class Employee only in class Manager onwards. line 6 will cause a compilation error. you are calling the getDetails() method that is present in both Employee and Manager class. When you do e.println(e. class Employee). the redundancy is now eliminated. With the given: 5 Employee e = new Manager(). // this is allowed 6 e.department = “Sales”. 4 public Date birthDate. In line 7. this process is called Virtual Method Invocation (VMI). // this is illegal 7 System. So. “poly” which means many and “morph” which means shapes or forms.Here's a revised version of the Employee and Manager code: 1 public class Employee { 2 public String name = "".department call. Engineer or even Secretary.. 8 } 9 } 1 2 3 4 5 6 7 public class Manager extends Employee { public String department. Director. 7 System.

salary and the department the Manager object belongs to. Polymorphic Arguments One of the benefits of Polymorphism is the use of Polymorphic Arguments. for (int i = 0. Directors. scjp Page 6 of 12 . etc). } This sample code will display all the details of all your Employees. what's the use of VMI? Let's say. Here's an example that we will revisit on the next Chapter. It returns the name. = new Manager().length. Secretary. = new Secretary(). Decamora III.java public class TestAnimal2 { public static void main(String args[]) { Mammal dog = new Mammal(). Prepared by: Lawrence G. i++) { System.getDetails()).We need to know that the Employee class' implementation of the getDetails() method only returns the name and salary while the Manager class' getDetails() implementation returns something more. i < staff. Animal // abstract +eat() +breath() +sleep() // non-abstract +play() Mammal Bird +eat() +breath() +sleep() +feedYoung() +eat() +breath() +sleep() +layEggs() +buildNests() Sample Code that uses Polymorphic Arguments: 1 2 3 4 5 6 // TestAnimal2. your boss wants you to display all the details of all your Employees (which includes. = new Employee().out. So.println(staff[i]. Managers. Your code will probably look like this: Employee staff[0] staff[1] staff[2] staff[] = new Employee[1024].

m. they cannot be accessed if we use the Animal reference type. In lines 9 and 10. Given lines 19 and 24.eat(). scjp .play(). This can be a convenient feature for the println() Page 7 of 12 Prepared by: Lawrence G. a. we need to test the reference type first so that an ClassCastException will not occur during runtime. Casting of Objects Lines 14 to 17 uses VMI.breath(). b. } else if (a instanceof Bird) { Bird b = (Bird) a. while other methods that are exclusive to the Mammal and Bird class. a. if you will examine the System class. doAnimalStuff(dog).sleep(). The instanceof operator The instanceof operator can be used to test what type of object was passed in the polymorphic argument. Decamora III.7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 } Bird eagle = new Bird(). For example. This feature enables you to have a convenient way in calling the needed method. there are several overloaded methods in most of the Java Classes. all having a different argument list. may it be a Mammal or Bird type.feedYoung(). doAnimalStuff(eagle). the method doAnimalStuff() can pass any type of Animal. But as a rule. before casting. if (a instanceof Mammal) { Mammal m = (Mammal)a. To be able to access the feedYoung() method of the Mammal class and the buildNest() and layEggs() method of the Bird class. Refer to lines 21 and 26 for object casting. a. as long as its a subclass of the class Animal. we need to cast our Animal reference type to the proper class type. b. } public static void doAnimalStuff(Animal a) { a. Overloading Methods Methods having the same name within the same class are known as overloaded methods.layEggs(). In the JavaAPI. you can use the instanceof operator with the if else or the if else if ladder to test the passed arguments. you will notice that there are multiple declarations of the print() and println() methods. } } Line 12 of the given example accepts any type of Animal.buildNest().

20.println(sum(10. Because the print() and the println() methods are overloaded methods. we can use var-args (variable arguments). you will see that there are several declarations of the sum method. 7 System. int num4) 18 { 19 return num1 + num2 + num3 + num4. 3 or 4 integer values.out. 20.out. It means the number of arguments can vary.out. 15 } 16 return total. 12 for (int n : num) 13 { 14 total += n. Starting Java 5. 20. 40)).. 30)). int num3) 14 { 15 return num1 + num2 + num3. Here's a sample code for this. so if the user needs to add up 2. 1 public class Overloading2 2 { 3 public static void main(String args[]) 4 { 5 System. int num2. 40)). 16 } 17 public static int sum(int num1. they just need to call System. 20. If they need to print something. 3 or 4 integer values. scjp . 8 } 9 public static int sum(int. 30. But this version also has its limitation. 30. Decamora III. 6 System.out.. 20 } 21 } In this example.out.println(sum(10. 12 } 13 public static int sum(int num1.println(sum(10. 6 System. 20)). 8 } 9 public static int sum(int num1. 30)).println(sum(10. Here's an sample code that displays method overloading: 1 public class Overloading1 2 { 3 public static void main(String args[]) 4 { 5 System. num) 10 { 11 int total = 0. 20)). there's a solution for this.println(sum(10. 17 } 18 } Page 8 of 12 Prepared by: Lawrence G. What if the user has more than 4 or more integer numbers? The given sample code is limited only to either 2. int num3.out.0.println() method. 7 System. No need to check on the argument type. all he needs to do is to call the sum methods and pass the integer values as arguments.method users. int num2) 10 { 11 return num1 + num2. int num2.println(sum(10.out.

out. Well. here's the actual rule.println("B"). We have what we call constructor chaining. but they are chained”.println("C").Notice line 9? The argument list is now using the var args notation. Consider this example: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 class A { A() { } System. Can we Inherit Constructors? No. } } public class ConstructorChaining { public static void main(String args[]) { C c = new C(). how come? In the previous paragraph it is said that Constructors are not inherited. but judging by the output it seems it that constructors of the super classes can be inherited. } } After instantiating the object of class C. “Constructors are not inherited.out. It means it can accept any amount of integer values as arguments in the method sum(). } } class C extends B { C() { System. but they are chained. Decamora III. 1 2 class A extends Object { Prepared by: Lawrence G. } class B extends A { B() { System. Constructors cannot be inherited. Java already made some changes. you will notice that the output is this: Output: A B C Now you will wonder. Here's another version of the given code. scjp Page 9 of 12 . The given example can is actually transformed by Java by inserting the super keyword in the first line of the constructor.out. in this example.println("A").

} } public class ConstructorChaining { public static void main(String args[]) { C c = new C(). As a rule.out. System.3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 A() { super(). Prepared by: Lawrence G. and 21. System. private double salary. Here's an sample code that demonstrates Constructor Overloading. How about line 1? Another rule. 13.out.out. The class Object is the mother of all classes. System. it automatically extends the class Object. scjp Page 10 of 12 .println("B"). } } class C extends B { C() { super(). Decamora III. Overloading Constructors Constructors are like methods that can also be overloaded. 1 2 3 4 5 public class Employee { private String name. If a class does not extends anything or any super class. the Java Programming Language will add a default call to super() in the first line of the constructor just like what you had in lines 5. } } Output: A B C This code will have the same output as the previous one. private MyDate birthDate. } } class B extends A { B() { super().println("C").println("A"). if a constructor does not have a call to this() or a call to super().

name = name. But in the absence of either of the two. a default call to super() will be in placed on the first line of the constructor. } public String getDetails() { return "Name: " + name + "\nSalary: " + salary + "\nBirth Date: " + birthDate. The wrapper classes can easily be memorized. salary. scjp . Just like in the previous example. Wrapper Class Boolean Byte Character Double Float Integer Long Short Primitive Data Type boolean byte char double float int long short Page 11 of 12 Prepared by: Lawrence G.6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 } private static final double BASE_SALARY = 15000. MyDate DoB) { this(name. } public Employee(String name. // Constructor public Employee(String name. this. is actually a call to a fellow constructor or a constructor within the same class. The call to this(). ConstructorChaining. } The Employee class has three constructors. Wrapper Classes are used to create an object type of a primitive value. Using the this() or super() is optional for all constructors. double salary.00. DoB). They are spelled out and all first characters are capilalized. they must be placed on the first line of the constructor. } public Employee(String name. Decamora III. MyDate DoB) { this.birthDate = DoB. this.java.salary = salary. null). Placing them elsewhere will cause a compilation error. Wrapper Classes A wrapper class. BASE_SALARY. while a call to super() is a call to the constructor of the super class. if incase that any of these two will be used. all constructors must have different argument lists. double salary) { this(name. is a class equivalent of all Java Primitive Data Types. just like the rule for method overloading. Another rule for the call to this() and call to super().

Because. Decamora III. // box-in // box-in // box-out In this example.How do we use Wrapper Classes? 7 8 9 10 int num = 100. we've declared an Integer object j with 200 as its value.intValue(). and in line 8. int num2 = j. we've declared an int primitive data type with 100 as its value. we've created an Integer object i with 100 as its object value. scjp .4 and earlier versions. line 10 is not allowed. Integer i = num.4 // and earlier versions In the early versions of Java. Is this statement legal? 11 int sum = i + j. Integer i = new Integer(num). Integer j = 200. In line 9. Integer j = new Integer(200). int sum = i + j. as we recall. i and j contains memory addresses of the object values. // This is illegal in Java 1. // // // // auto auto auto auto box-in box-in box-out box-out Page 12 of 12 Prepared by: Lawrence G. say 1. But starting Java 5.0 up to the present versions. int num2 = j. We can now rewrite the previous example this this manner by applying AutoBox-In and AutoBox-Out 7 8 9 10 11 int num = 100. a new feature called AutoBox-In and AutoBox-Out was introduced.

Master your semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master your semester with Scribd & The New York Times

Cancel anytime.