cis3023: programming fundamentals for cis majors ii summer 2010 viswanathan inheritance and...

45
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

Upload: calvin-higgins

Post on 30-Dec-2015

216 views

Category:

Documents


0 download

TRANSCRIPT

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

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

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

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

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

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

}

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

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

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

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:

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

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

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

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

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

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.

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

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

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

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

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

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

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

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!

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

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

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

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

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

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

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

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

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

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

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

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!

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

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

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

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!

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

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}

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

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

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

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

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

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}

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

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

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

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

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

Casting between Superclass and Subclass

Implicit casting

Student z = new GraduateStudent();

Explicit casting

GraduateStudent gz = (GraduateStudent)z;

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

Class HierarchyOver time, we build up an inverted ‘tree’ of

classes that are interrelated through inheritance

parent class, superclass, ancestor;

child class, subclass, descendant

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

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

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

Some Methods from Object class

• String toString()• boolean equals(Object object)• Class getClass()• Object clone()

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

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.

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

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:

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

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

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

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

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

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”

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

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

}

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

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

}

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

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

}

}

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

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;

elsereturn false;

} else {return false;

}}

}

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

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

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

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

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

The clone() Method

• takes no arguments and returns a copy of the calling object.

Example:

int[] targetArray = (int[]) sourceArray.clone();

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

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.

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

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

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

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