CIS3023: Programming Fundamentals for CIS Majors II Summer 2010
description
Transcript of CIS3023: Programming Fundamentals for CIS Majors II Summer 2010
CIS3023: Programming Fundamentals for CIS Majors IISummer 2010
Viswanathan
Inheritance and Polymorphism
Course Lecture Slides2nd June 2010
“ We are all gifted. That is our inheritance. ” --Ethel Waters
Ganesh
Inheritance• Inheritance is the capability of a class to use the
properties and methods of another class while adding its own functionality.
• A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class).
Inheritance
• It allows us to define a general class and then specialize it simply by adding more attributes and adding/changing methods
Syntax: class <SpecialClass> extends <GeneralClass> {
// new attributes // new or changed methods
}
public class Student { private String name = “N/A”; private String ssn = “N/A”; private float gpa = 0.0f;
// constructors, get/set methods not shown here
public void print() { System.out.println( name + “ " + ssn
+ " " + gpa); }}
public class GraduateStudent extends Student{ private String ugDegree; private String ugInst;}
Inheritance and Methods
public class Main { public static void main(String[] args){ GraduateStudent s1 = new GraduateStudent(); s1.print(); }}
GraduateStudent class inherits all the attributes and the print( ) method
> java MainN/A N/A 0.0
Output:
public class Student { public String name = “”; public String major = “”; public float gpa = 0.0f; public void print() { System.out.println( name + “ ” + major + “ ” + gpa); }}
public class GraduateStudent extends Student{ private String ugDegree; private String ugInstitution; public void print() {
System.out.println(name + “ ” + major + “ ” + gpa);System.out.println(ugDegree + “ ” + ugInst);
}}
Method Overriding
public class GraduateStudent extends Student{ private String ugDegree; private String ugInstitution; public void print() {
super.print();System.out.println(ugDegree + “ ” + ugInst);
}}
public class Student { public String name = “”; public String major = “”; public float gpa = 0.0f; public void print() { System.out.println( name + “ ” + major + “ ” + gpa); }}
Method Overriding
Method Overriding
• Can change the implementation of the method but cannot change the method signature.
• If you change the signature of a method -- this results in method overloading.
public class Student { private String name = “”; private String major = “”; private float gpa = 0.0f; public void print() { System.out.println( name + “ ” + major + “ ” + gpa); }}
public class GraduateStudent extends Student{ private String ugDegree; private String ugInstitution; public void print(String filename) {
// code to print the graduate student information // to the file called ‘filename’
}}
Method Overloading
public class GraduateStudent extends Student{ private String ugDegree; private String ugInstitution; public void print(String filename) {
int sName = name; // code to print the graduate student information // to the file called ‘filename’
}}
public class Student { private String name = “”; private String major = “”; private float gpa = 0.0f; public void print() { System.out.println( name + “ ” + major + “ ” + gpa); }}
Inheritance and Methods
public class Main { public static void main(String[] args){ GraduateStudent s1 = new GraduateStudent(); s1.print(); // legal? }}
GraduateStudent class inherits all the attributes and the print( ) method
public class Student { private String name; private String studentId; private String majorField; private double gpa; private int credits; // Other details omitted.}
public class GraduateStudent extends Student { String ugDegree; String ugInstitution; public void UpdateGpa(int c, int gr) {
gpa += (gpa*credits + c*gr)/(credits + c); credits += c;
}}
Inheritance and Visibility
Compiler Error because gpa and credits are private and hence can not be accessed directly!
public class Student { private String name; private String studentId; private String majorField; protected double gpa; protected int credits; // Other details omitted.}
public class GraduateStudent extends Student { String ugDegree; String ugInstitution; public void UpdateGpa(int c, int gr) {
gpa += (gpa*credits + c*gr)/(credits + c); credits += c;
}}
Inheritance and Visibility
Now, there is no Compiler Error here
Accessibility Summary
Modifier on members in a class
Accessed from the same class
Accessed from the same package
Accessed from a subclass
Accessed from a different package
public
protected -
default - -
private - - -
Inheritance and ConstructorsConstructors are not inherited
15
public class Student { protected String name; protected String ssn; public Student(String n, String s) {
setName(n); setSsn(s); } public Student(){ this(“?”, “?”); } // other details not shown here}class GradStudent extends Student{ String ugDegree; String ugInst; // no constructor defined}
static void Main(string[] args){ Student s = new Student("Joe“, “111-11-1111”); //ok! Student g = new GradStudent("Fred“, “111-11-1111”);
// NOT OK!}
Inheritance and ConstructorsWe have to explicitly create constructors in the subclass
16
public class Student { protected String name; protected String ssn; public Student(String n, String s) {
setName(n); setSsn(s); } public Student(){ this(“?”, “?”); } // other details not shown here}class GradStudent extends Student{ String ugDegree; String ugInst; public GradStudent(String n, String s){
setName(n); setSsn(s); setUgDegree(“?”); setUgInst(“?”);}
}
static void main(string[] args){ Student s = new Student("Joe“, “111-11-1111”); GradStudent s = new GradStudent("Fred“, “111-11-1111”); }
Inheritance and ConstructorsWe have to explicitly create constructors in the subclass
17
public class Student { protected String name; protected String ssn; public Student(String n, String s) {
setName(n); setSsn(s); } public Student(){ this(“?”, “?”); } // other details not shown here
}class GradStudent extends Student{ String ugDegree; String ugInst; public GradStudent(String n, String s){
super(n, s); setUgDegree(“?”); setUgInst(“?”);}}
static void main(string[] args){ Student s = new Student("Joe“, “111-11-1111”); GradStudent s = new GradStudent("Fred“, “111-11-1111”); }
Inheritance and Constructors
• whenever a constructor for a subclass is called, constructor(s) for all of its ancestor class(es) are also called, either explicitly or by default –
in top-to-bottom order.
• This is called Constructor Chaining!
Inheritance and Constructors
19
public class Student { protected String name; protected String ssn; public Student(String n, String s) {
setName(n); setSsn(s); } // no other constructor is defined // other details not shown here
}class GradStudent extends Student{ String ugDegree; String ugInst; public GradStudent(String n, String s){
setName(n); setSsn(s); setUgDegree(“?”); setUgInst(“?”);}
}
static void main(string[] args){ Student s = new Student("Joe“, “111-11-1111”); GradStudent s = new GradStudent("Fred“, “111-11-1111”); }
Error!
Student.java:19: cannot find symbolsymbol : constructor Std()location: class Std public GradStudent(String n, String s) { ^1 error
// line #19
Inheritance and Constructors
20
public class Student { protected String name; protected String ssn; public Student(String n, String s) {
setName(n); setSsn(s); } // no other constructor is defined // other details not shown here
}class GradStudent extends Student{ String ugDegree; String ugInst; public GradStudent(String n, String s){
super(n,s); setUgDegree(“?”); setUgInst(“?”);}
}
static void main(string[] args){ Student s = new Student("Joe“, “111-11-1111”); GradStudent s = new GradStudent("Fred“, “111-11-1111”); }
Woohoo! Fixed!
21
public class Student { private String name = “”; private String ssn = “”; private String major = “”; private float gpa = 0.0f; public Student(String n) { setName(n);} public void print() { System.out.print(name); } // other details not shown here}
public class GraduateStudent extends Student{ private String ugDegree; private String ugInst; public GraduateStudent(String n, String ug, String uI) {
super(n); setUgDegree(ug); setUgInst(uI); } public void print() {
super.print(); System.out.println(“ is a Graduate Student”); } // other details not shown here}
public class UnderGraduateStudent extends Student{ private String highSchool; public UnderGraduateStudent(String n, String h) {
super(n); highSchool = h; } public void print() {
super.print(); System.out.println((“ is a UndergraduateStudent”); } // other details not shown here}
static void main(string[] args) {
Student[] studentBody = new Student[20];
UnderGraduateStudent u1 = new UnderGraduateStudent(“John”,“GNV High”); GraduateStudent g1 = new GraduateStudent(“Jack”, “CIS”, “UF”);
studentBody[0] = u1; studentBody[1] = g1; for (int i = 0; i < 20; i++) if(studentBody[i]!= null) studentBody[i].print();}
Output:
John is a Undergraduate StudentJack is a Graduate Student
Polymorphism
• The ability of two or more objects belonging to different classes to respond to exactly the same message in different class-specific ways.
• It illustrates ‘late binding’.
24
public class Student { protected String name = “”; private String ssn = “”; private String major = “”; private float gpa = 0.0f; public Student(String n) { setName(n);}
// no print() method// other details not shown here
}
public class GraduateStudent extends Student{ private String ugDegree; private String ugInst; public GraduateStudent(String n, String ug, String uI) {
super(n); setUgDegree(ug); setUgInst(uI); } public void print() {
System.out.println(name + “ is a Graduate Student”); } // other details not shown here}
public class UnderGraduateStudent extends Student{ private String highSchool; public UnderGraduateStudent(String n, String h) {
super(n); highSchool = h; } public void print() {
System.out.println(name + “ is a UndergraduateStudent”); } // other details not shown here}
static void main(string[] args) {
Student[] studentBody = new Student[20];
UnderGraduateStudent u1 = new UnderGraduateStudent(“John”,“GNV High”); GraduateStudent g1 = new GraduateStudent(“Jack”, “CIS”, “UF”);
studentBody[0] = u1; studentBody[1] = g1; for (int i = 0; i < 20; i++) if(studentBody[i]!= null)
studentBody[i].print(); // line #15. will it work?}
Driver.java:15: cannot find symbolsymbol : method print()location: class Student studentBody[i].print(); // line #15. will it work? ^1 error
Inheritance: "Is A" Relationship
If GraduateStudent is a subclass of Student, then a GraduateStudent IS A Student
Anything that we say about a Student's behavior or data structure MUST also be true of a GraduateStudent
Casting between Superclass and Subclass
Implicit casting
Student z = new GraduateStudent();
Explicit casting
GraduateStudent gz = (GraduateStudent)z;
Class HierarchyOver time, we build up an inverted ‘tree’ of
classes that are interrelated through inheritance
parent class, superclass, ancestor;
child class, subclass, descendant
The Root of all Classes: Object• Every class in Java has descended from the java.lang.Object class.
• If no inheritance is specified when a class is defined, the superclass of the class is java.lang.Object class
public class Circle { ... }
Equivalent public class Circle extends Object { ... }
Some Methods from Object class
• String toString()• boolean equals(Object object)• Class getClass()• Object clone()
The toString() method
public class Student { private String name = “”; private String ssn = “”; private String major = “”; private float gpa = 0.0f; public Student(String n) { name = n;}
public String toString() { return(name + “ “ + ssn + “ “ + major + “ “ + gpa); }}
• Intended to return a string representation of
the object.
The toString() method
The default implementation returns • a string consisting of a class name of which the object is an instance, • the at sign (@), and • a number representing this object.
Student s = new Student( );System.out.println (s.toString( ));
Student@126b249Output:
Example
public class Main {public static void main(String[] args) {
Course c1 = new Course(“Java Prog. II”, “CIS 3023”, 1);Course c2 = new Course(“Java Prog. II”, “CIS 3023”, 2);
// Find out if both c1 and c2 are same course?// How can I do it?
}}
class Course {private String courseName;private int courseNo;private String offering;
private int sectionNo;
// other details not shown here…}
public class Main {public static void main(String[] args) {
Course c1 = new Course(“Java Prog. II”, “CIS 3023”, 1);Course c2 = new Course(“Java Prog. II”, “CIS 3023”, 1);
// Find out if both c1 and c2 are same?boolean b = (c1 == c2); // will this work?System.out.println(“Is c1==c2? ” + b);
}}
class Course {private String courseName;private int courseNo;private String offering;
private int sectionNo;
// other details not shown here…}
Example
The equals() method
• intends to compare the contents (“values”) of two objects
• default implementation compares object references
• override equals() in a class to define when two objects of the that class will be considered as “equal”
36
public class Main {public static void main(String[] args) {
Course c1 = new Course(“Java Prog. II”, “CIS 3023”, 1);Course c2 = new Course(“Java Prog. II”, “CIS 3023”, 2);
// Find out if both c1 and c2 are same?boolean b = (c1.equals(c2));
}}
class Course {private String courseName; private int courseNo;private String offering; private int sectionNo;
// other details not shown here…
public boolean equals(Object o) { if(o instanceof Course) { if(courseNo == o.getCourseNo())
return true;else
return false; } else {
return false; }}
}
37
public class Main {public static void main(String[] args) {
Course c1 = new Course(“Java Prog. II”, “CIS 3023”, 1);Course c2 = new Course(“Java Prog. II”, “CIS 3023”, 2);
// Find out if both c1 and c2 are same?boolean b = (c1.equals(c2));
}}
class Course {private String courseName; private int courseNo;private String offering; private int sectionNo;
// other details not shown here…
public boolean equals(Object o) { if(o instanceof Course) { if(courseNo == o.getCourseNo()) // is it ok?
return true;else
return false; } else {
return false; }}
}
38
class Course {private String courseName; private int courseNo;private String offering; private int sectionNo;
// other details not shown here…
public boolean equals(Object o) { if(o instanceof Course) { Course c = (Course)o;
if(courseNo == c.getCourseNo()) // now ok!return true;
elsereturn false;
} else {return false; }
}}
public class Main {public static void main(String[] args) {
Course c1 = new Course(“Java Prog. II”, “CIS 3023”, 1);Course c2 = new Course(“Java Prog. II”, “CIS 3023”, 2);
// Find out if both c1 and c2 are same?boolean b = (c1.equals(c2));
}}
39
public class Main {public static void main(String[] args) {
Course c1 = new Course(“Java Prog. II”, 3023, 1);Course c2 = new Course(“Java Prog. II”, 3023, 2);
// Find out if both c1 and c2 are sameboolean b = (c1.equals(c2));
}}
class Course {private String courseName; private int courseNo;private String offering; private int sectionNo;
// other details not shown here…
public boolean equals(Object o) { if(o instanceof Course) { Course c = (Course)o;
if(courseNo == c.getCourseNo()&& courseName.equals(c.getCourseName()))return true;
elsereturn false;
} else {return false;
}}
}
Comparing Strings• You have used the the equals() method of the String class to compare strings.
String s1 = new String("Hello World!");String s2 = new String("Hello World!");
if(s1 == s2) System.out.println("true");else System.out.println("false"); // will print false
if (s1.equals(s2)) System.out.println("true");else System.out.println("false"); // will print true
The getClass() Method
public class Main {public static void main(String[] args) {
Course c = new Course(“Java Prog. II”, “CIS 3023”, 1);
System.out.println( c.getClass() ); }
}
Output:class Course
The clone() Method
• takes no arguments and returns a copy of the calling object.
Example:
int[] targetArray = (int[]) sourceArray.clone();
Can we call the clone method on any object?
The clone() Method
No! Only objects of classes that implement the Cloneable interface can be cloned
Further material on interfaces coming up… a little later.
The final Modifier• can be used to prevent classes from being
extended or a method from being overridden.
Declaring a final class:
The final method cannot be overridden by its subclasses.
final class Math { ...}
Get more info!• Inheritance and Polymorphism:
http://home.cogeco.ca/~ve3ll/jatutor5.htm• Java Class hierarchy:
http://java.sun.com/docs/books/tutorial/java/IandI/subclasses.html
• The Object Class in Java: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html
• A Good book! http://www.horstmann.com/corejava.html