Presentation is loading. Please wait.

Presentation is loading. Please wait.

CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Viswanathan Inheritance and Polymorphism Course Lecture Slides 2 nd June 2010 “ We are.

Similar presentations


Presentation on theme: "CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Viswanathan Inheritance and Polymorphism Course Lecture Slides 2 nd June 2010 “ We are."— Presentation transcript:

1 CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Viswanathan Inheritance and Polymorphism Course Lecture Slides 2 nd June 2010 “ We are all gifted. That is our inheritance. ” --Ethel Waters Ganesh

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

3 Inheritance It allows us to define a general class and then specialize it simply by adding more attributes and adding/changing methods Syntax: class extends { // new attributes // new or changed methods }

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

5 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 Main N/A N/A 0.0 Output:

6 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

7 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

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

9 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

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

11 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

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

13 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

14 Accessibility Summary

15 Inheritance and Constructors Constructors 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! }

16 Inheritance and Constructors We 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”); }

17 Inheritance and Constructors We 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”); }

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

19 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 symbol symbol : constructor Std() location: class Std public GradStudent(String n, String s) { ^ 1 error // line #19

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

22 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 Student Jack is a Graduate Student

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

25 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 symbol symbol : method print() location: class Student studentBody[i].print(); // line #15. will it work? ^ 1 error

26 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

27 Casting between Superclass and Subclass Implicit casting Student z = new GraduateStudent(); Explicit casting GraduateStudent gz = (GraduateStudent)z;

28 Class Hierarchy Over time, we build up an inverted ‘tree’ of classes that are interrelated through inheritance parent class, superclass, ancestor; child class, subclass, descendant

29 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

30 Some Methods from Object class String toString() boolean equals(Object object) Class getClass() Object clone()

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

32 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@126b249 Output:

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

34 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

35 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 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 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 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; else return 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 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 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) { Course c = (Course)o; if(courseNo == c.getCourseNo() && courseName.equals(c.getCourseName())) return true; else return false; } else { return false; } } }

40 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

41 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

42 The clone() Method takes no arguments and returns a copy of the calling object. Example: int[] targetArray = (int[]) sourceArray.clone();

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

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

45 Get more info! Inheritance and Polymorphism: http://home.cogeco.ca/~ve3ll/jatutor5.htm http://home.cogeco.ca/~ve3ll/jatutor5.htm Java Class hierarchy: http://java.sun.com/docs/books/tutorial/java/Ian dI/subclasses.html http://java.sun.com/docs/books/tutorial/java/Ian dI/subclasses.html The Object Class in Java: http://java.sun.com/j2se/1.5.0/docs/api/java/lan g/Object.html http://java.sun.com/j2se/1.5.0/docs/api/java/lan g/Object.html A Good book! http://www.horstmann.com/corejava.html http://www.horstmann.com/corejava.html


Download ppt "CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Viswanathan Inheritance and Polymorphism Course Lecture Slides 2 nd June 2010 “ We are."

Similar presentations


Ads by Google