1 / 30

Intro to CS – Honors I Inheritance and Polymorphism

Intro to CS – Honors I Inheritance and Polymorphism. Georgios Portokalidis gportoka@stevens.edu. Inheritance. Generic class. More specialized classes. Even more Specialized classes. Why Inheritance?. You can define or use a generic class

korbin
Download Presentation

Intro to CS – Honors I Inheritance and Polymorphism

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Intro to CS – Honors IInheritance and Polymorphism Georgios Portokalidis gportoka@stevens.edu

  2. Inheritance Generic class More specialized classes Even more Specialized classes

  3. Why Inheritance? • You can define or use a generic class • Later, you can define a more a specialized class that inherits the properties of the generic class

  4. Persons in Stevens What kind of properties are shared by all persons? What kind of properties are shared by students?

  5. public class Person • { • private String name; • public Person() • { • name = "No name yet"; • } • public Person(String initialName) • { • name = initialName; • } • public void setName(String newName) • { • name = newName; • } • public String getName() • { • return name; • } • public void writeOutput() • { • System.out.println("Name: " + name); • } • public booleanhasSameName(Person otherPerson) • { • return this.name.equalsIgnoreCase(otherPerson.name); • } • }

  6. Students in Stevens public class Student extends Person { private intstudentNumber; public intgetStudentNumber() { return studentNumber; } public void setStudentNumber(intnewStudentNumber) { studentNumber = newStudentNumber; } } • All students are persons • All students have a student number • We want a class that inherits all properties of a person but includes a student number • The class Student inherits all public methods and attributes of Person • It can add its own instance variables and methods Private is private! Can I access Person’s name?

  7. Using Derived Classes The default constructor of Student, which in turn by default invokes the default constructor of its base class public class InheritanceDemo { public static void main(String[] args) { Student s = new Student(); s.setName("Warren Peace") s.setStudentNumber(1234); } } Which constructor is called? This method is inherited This method is only defined in Student

  8. When to Use Inheritance • If an is-a relationship does not exist between two proposed classes, do not use inheritance to derive one class from the other • It could be a has-a relationship • Define an object of one class as an instance variable within the other class • SYNTAX • public class Derived_Class_NameextendsBase_Class_Name • { • Declarations_of_Added_Instance_Variables • Definitions_of_Added__And_Changed_Methods • }

  9. Using Derived Classes public class InheritanceDemo { public static void main(String[] args) { Student s = new Student(); s.setName("Warren Peace") s.setStudentNumber(1234); s.writeOutput(); } } Name: Warren Peace Invokes method of Person

  10. Overriding public class Student extends Person { … public void writeOutput() { System.out.println("Name: " + getName()); System.out.println("Student Number: " + studentNumber); } } You can define a new method with the same heading which overrides the inherited one

  11. Using Derived Classes public class InheritanceDemo { public static void main(String[] args) { Student s = new Student(); s.setName("Warren Peace") s.setStudentNumber(1234); s.writeOutput(); } } Name: Warren Peace Student Number: 1234

  12. Overriding is not Overloading public class Student extends Person { … public String getName(String title) { return title + getName(); } } public class Person { private String name; … public String getName() { return name; } } public class Student extends Person { … public char[] getName(String title) { return title + getName(); } } Cannot override with the same signature and different return type

  13. Preventing Overriding public class Person { private String name; … public final String getName() { return name; } } Final classes cannot be extended Final methods cannot be overriden public final class Person { private String name; … public final String getName() { return name; } }

  14. UML Inheritance Diagrams

  15. How About Constructors public class Student extends Person { private intstudentNumber; public Student() { super(); studentNumber = 0; } public Student(String initialName, intinitialNumber) { super(initialName); studentNumber = InitialNumber; } } public class Student extends Person { private intstudentNumber; public Student() { name = "No name yet"; studentNumber = 0; } public Student(String initialName, intinitialNumber) { setName(initialName); studentNumber = InitialNumber; } } What’s bad with this? Call the constructor of the parent/base class super() behaves as this(). Must be the first action in the constructor Call the constructor of the parent/base class

  16. How About Constructors public class Student extends Person { private intstudentNumber; public Student() { studentNumber = 0; } public Student(String initialName, intinitialNumber) { studentNumber = InitialNumber; } } The default constructor is always called if super() is missing What is the value of an object’s instance variables after using these constructors?

  17. Use super to Refer to the Base Class public class Student extends Person { … public void writeOutput() { System.out.println("Name: " + super.getName()); System.out.println("Student Number: " + studentNumber); } }

  18. Use super to Call Overridden Methods public class Student extends Person { … public void writeOutput() { System.out.println("Name: " + super.getName()); super.writeOutput(); } }

  19. Beware of Overriding vs Overloading public class Person { private String name; public void reset(String newName) { name = newName; } } public class Student extends Person { private intstudentNumber; public void reset(String newName, intnewNumber) { setname(newName); name = newName; } } Java SE 8 is introducing annotations @Override can be used to force the compiler to produce an error if you are not actually overriding a method @Override

  20. Multiple Inheritance public class Person { … } Not possible public class Student extends Person { … } public class Undergraduate extends Student { … } public Undergraduate() { super.super.writeOutput(); }

  21. Type Compatibility • An Undergrad is a Student is a Person public class SomeClass { public static void compareNumbers(Student s1, Student s2) { if (s1.getStudentNumber() == s2.getStudentNumber()) System.out.println(s1.getName() + " has the same " + "number as " + s2.getName()); else System.out.println(s1.getName() + " has a different“ + "number than " + s2.getName()); } . . . } Student studentObject = new Student("Jane Doe", 1234); Undergraduate undergradObject = new Undergraduate("Jack Buck", 1234, 1); SomeClass.compareNumbers(studentObject, undergradObject);

  22. Type Compatibility • Note that this is not automatic type casting • An object can have multiple types • An Undergrad is also of the type Student and Person • The reverse is not true • A Person is not always a Student • Nor a Student always an Undergrad

  23. The Object Class • Java has an “Eve” class that is the ancestor of every class • Every class you write implicitly “extends” Object • public class SomeClassextends Object • { • … • } • You can write methods that take an Object type as parameter that will accept any object • Can I pass a primitive type to such methods? • Every class inherits toString() and equals() from Object • Do not expect these to work properly

  24. Type Casting to Successor Classes • Example: overriding the defaults equals method • public boolean equals(Object otherObject) • We could declare public booleanequals(Student otherStudent) • What is the problem with this? • To override we need to declare Different headings mean we are overloading • public boolean equals(Object otherObject) • { • Student otherStudent = (Student)otherObject; • return this.hasSameName(otherStudent) && • (this.studentNumber == otherStudent.studentNumber); • }

  25. Type Casting to Successor Classes • public boolean equals(Object otherObject) • { • Student otherStudent = (Student)otherObject; • return this.hasSameName(otherStudent) && • (this.studentNumber == otherStudent.studentNumber); • } • Student oneStudent, otherStudent; • … • if (oneStudent.equals(otherStudent)) • { • … • } How can this go bad? • String notAStudent; • … • if (oneStudent.equals(notAStudent)) • … This will cause a run-time error, since the error cannot be detected at compile time

  26. The instanceof Operator • public boolean equals(Object otherObject) • { • booleanisEqual = false; • if ((otherObject != null) && • (otherObjectinstanceof Student)) • { • Student otherStudent = (Student)otherObject; • isEqual = this.sameName(otherStudent) && • (this.studentNumber== otherStudent.studentNumber); • } • return isEqual; • } SYNTAX Object instanceofClass_Name Returns true if the object is of type Class_Name

  27. Multiple Inheritance public class ClassA extends Object { public void doSomething() { System.out.println("doSomething implementation of A"); }//ClassA own method public void methodA(){ } } Object It is impossible to decide which method to call. Java avoids the diamond problem by disallowing multiple inheritance public class ClassB extends Object { public void doSomething() { System.out.println("doSomething implementation of B"); }//ClassB own method public void methodB(){ } } ClassA ClassB public class ClassC extends ClassB, ClassA { public void test() { doSomething(); } } ClassC Which method will be called?

  28. Polymorphism • “Polymorphism allows you to make changes in the method definition for the derived classes and have those changes apply to the methods written in the base class.” Let’s use a for-each loop to print all Persons information Person[] people = new Person[4]; people[0] = new Undergraduate("Cotty, Manny", 4910); people[1] = new Undergraduate("Kick, Anita", 9931); people[2] = new Student("DeBanque, Robin", 8812); people[3] = new Undergraduate("Bugg, June", 9901); for (Person p: people) { p.writeOutput(); System.out.println(); } Which writeOutput() will be called? In Java this is called dynamic binding or late binding Even though we are using object references of type Person the methods of the child-class objects are called

  29. Polymorphism • REMEMBER Objects Know How They Are Supposed to Act • The method that is to be called is determined at run time, and it does not depend on an the type of an object reference but the actually object • Java always assumes late binding • Some other languages allow you to control which methods will use late binding

More Related