Chapter 13. Inheritance and Polymorphism. CS 180 Sunil Prabhakar Department of Computer Science Purdue University
|
|
- Suzanna Simon
- 5 years ago
- Views:
Transcription
1 Chapter 13 Inheritance and Polymorphism CS 180 Sunil Prabhakar Department of Computer Science Purdue University
2 Introduction Inheritance and polymorphism are key concepts of Object Oriented Programming. Inheritance facilitates the reuse of code. A subclass inherits members (data and methods) from all its ancestor classes. The subclass can add more functionality to the class or replace some functionality that it inherits. Polymorphism simplifies code by automatically using the appropriate method for a given object. Polymorphism also makes it easy to extend code. 2
3 Inheritance A superclass corresponds to a general class, and a subclass is a specialization of the superclass. E.g. Account, Checking, Savings. Behavior and data common to the subclasses is often available in the superclass. E.g. Account number, owner name, data opened. Each subclass provides behavior and data that is relevant only to the subclass. E.g. Minimum balance for checking a/c, interest rate and computation for savings account. The common behavior is implemented once in the superclass and automatically inherited by the subclasses. 3
4 Defining Classes with Inheritance Case Study: Suppose we want implement a class roster that contains both undergraduate and graduate students. Each student s record will contain his or her name, three test scores, and the final course grade. The formula for determining the course grade is different for graduate students than for undergraduate students. 4
5 Modeling Two Types of Students There are two ways to design the classes to model undergraduate and graduate students. We can define two unrelated classes, one for undergraduates and one for graduates. We can model the two kinds of students by using classes that are related in an inheritance hierarchy. Two classes are unrelated if they are not connected in an inheritance relationship. NOTE: all classes inherit from Object 5
6 Classes for the Class Roster For the Class Roster sample, we design three classes: Student UndergraduateStudent GraduateStudent The Student class will incorporate behavior and data common to both UndergraduateStudent and GraduateStudent objects. The UndergraduateStudent class and the GraduateStudent class will each contain behaviors and data specific to their respective objects. 6
7 Creating a subclass We use the keyword extends in the class header to declare that it is a subclass: public class GraduateStudent extends Student { Student is the superclass, parent, or base class. A parent (of a parent ) is an ancestor class. GraduateStudent is the subclass, child, or derived class. A child (of a child...) is a descendent class. If a class does have the extend keyword, then it derives from the Object class. 7
8 Example: Student class Student { protected final static int NUM_OF_TESTS = 3; protected String name; protected int[] test; protected String coursegrade; public Student( ) { this("no Name"); public Student(String studentname) { name = studentname; test = new int[num_of_tests]; coursegrade = "****"; public String getcoursegrade( ) { return coursegrade; public String getname( ) { return name; public int gettestscore(int testnumber) { return test[testnumber-1]; public void setname(string newname) { name = newname; public void settestscore(int testnumber, int testscore) { test[testnumber-1] = testscore; public void computecoursegrade(); 8
9 Example: GraduateStudent class GraduateStudent extends Student{ public void computecoursegrade() { int total = 0; for (int i = 0; i < NUM_OF_TESTS; i++) { total += test[i]; if (total / NUM_OF_TESTS >= 80) { coursegrade = "Pass"; else { coursegrade = "No Pass"; 9
10 Example: UndergraduateStudent class UndergraduateStudent extends Student{ public void computecoursegrade() { int total = 0; for (int i = 0; i < NUM_OF_TESTS; i++) { total += test[i]; if (total / NUM_OF_TESTS >= 70) { coursegrade = "Pass"; else { coursegrade = "No Pass"; 10
11 Inheritance Hierarchy Student New visibility modifier: # protected + NUM_OF_TESTS # name # test # coursegrade + Student(): void + Student(String): void + getcoursegrade(): String + getname(): String + gettestscore(int): int + setname(string): void + settestscore(int, int): void UndergraduateStudent GraduateStudent + computecoursegrade(): void + computecoursegrade(): void 11
12 Overriding All non-private members of a class are inherited by derived classes This includes instance and class members A derived class may however, override an inherited method Data members can also be overridden but should be avoided since it only creates confusion. To override a method, the derived class simply defines a method with the same name, number and types of parameters (same signature) An overridden method cannot change the return type! A subclass may overload any method (inherited or otherwise) by using the same name, but different signature. 12
13 Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 13
14 Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 13
15 Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 13
16 Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 13
17 Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 13
18 Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); sub.methoda(i); sub.methoda(c); sup.methoda(c); overloaded Sup methoda(int i){ Sub methoda(char c){ 13
19 Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 13
20 Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 13
21 Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; Sup methoda(int i){ sup.methoda(); sup.methoda(i); sub.methoda(); sub.methoda(i); sub.methoda(c); sup.methoda(c); overridden Sub methoda(char c){ 13
22 Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 13
23 Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 13
24 Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); sub.methoda(i); sub.methoda(c); sup.methoda(c); inherited Sup methoda(int i){ Sub methoda(char c){ 13
25 Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 13
26 Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 13
27 Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; Sup methoda(int i){ sup.methoda(); sup.methoda(i); sub.methoda(); sub.methoda(i); sub.methoda(c); sup.methoda(c); overridden & overloaded Sub methoda(char c){ 13
28 Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 13
29 Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 13
30 Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Overloaded & Auto cast Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 13
31 Overriding and overloading Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c = 'c'; sup.methoda(); sup.methoda(i); sub.methoda(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 13
32 Limiting inheritance and overriding If a class is declared to be final, then no other classes can derive from it. public final class ClassA If a method is declared to be final, then no derived class can override this method. A final method can be overloaded in a derived class though. public final void methoda() 14
33 The protected Modifier The modifier protected makes a data member or method visible and accessible only to instances of the class and descendant classes. public data members and methods are accessible to everyone. private data members and methods are accessible only to instances of the class. protected is similar to: public for descendant classes private for any other class 15
34 Inheritance and Member Accessibility We use the following visual representation of inheritance to illustrate data member accessibility. public protected private Accessible Inaccessible 16
35 Inheritance and Member Accessibility We use the following visual representation of inheritance to illustrate data member accessibility. public protected private Super Accessible Inaccessible Sub Class Hierarchy 16
36 Inheritance and Member Accessibility We use the following visual representation of inheritance to illustrate data member accessibility. public protected private Super :Super Instances Accessible Inaccessible Sub :Sub :Super This shows the inherited components of the superclass are part of the subclass instance Class Hierarchy 16
37 The Effect of the Visibility Modifiers public protected private :Super Accessible Inaccessible :Client :Sub :Super Accessibility from a Client method 17
38 The Effect of the Visibility Modifiers public protected private :Super Accessible Inaccessible :Client :Sub :Super Accessibility from a Client method Only public members, those defined for the class and those inherited, are visible from outside. All else is hidden from the outside. 17
39 The Effect of the Visibility Modifiers public protected private :Super Accessible Inaccessible :Client :Sub :Super Accessibility from a Client method Only public members, those defined for the class and those inherited, are visible from outside. All else is hidden from the outside. 17
40 The Effect of the Visibility Modifiers public protected private :Super Accessible Inaccessible :Client Accessibility from a Client method :Sub :Super Only public members, those defined for the class and those inherited, are visible from outside. All else is hidden from the outside. 17
41 The Effect of the Visibility Modifiers public protected private :Super Accessible Inaccessible :Client Accessibility from a Client method Only public members, those defined for the class and those inherited, are visible from outside. All else is hidden from the outside. :Sub :Super 17
42 The Effect of the Visibility Modifiers public protected private :Client :Super Accessible Inaccessible Accessibility from a Client method Only public members, those defined for the class and those inherited, are visible from outside. All else is hidden from the outside. :Sub :Super 17
43 Accessibility of Super from Sub public protected private Accessibility from a method of the Sub class :Super :Sub 18
44 Accessibility of Super from Sub public protected private Accessibility from a method of the Sub class :Super :Sub From a method of the Sub, everything is visible except the private members of its super class. 18
45 Accessibility of Super from Sub public protected private Accessibility from a method of the Sub class :Super :Sub From a method of the Sub, everything is visible except the private members of its super class. 18
46 Accessibility of Super from Sub public protected private Accessibility from a method of the Sub class From a method of the Sub, everything is visible except the private members of its super class. :Super :Sub 18
47 Accessibility from Another Instance Data members accessible from an instance are also accessible from other instances of the same class. one:classa two:classa This could be private, Protected, or public. 19
48 Inheritance and Constructors Unlike members of a superclass, constructors of a superclass are not inherited by its subclasses. As always, each class that does not define a constructor is automatically given a default constructor. In addition, in each constructor of a derived class, we must make a call to the constructor of the base class by calling: super(); This must be the first statement in the constructor. If this statement is not present, the compiler automatically adds it as the first statement. You may optionally call some other constructor of the base class, e.g.: super( some string ); 20
49 Constructors and inheritance The constructor for each class can be used to initialize the variables defined in that class. For all classes, calls to the constructors are chained all the way back to the constructor for the Object class. Recall that it is also possible to call another constructor of the same class using the this keyword. However, this must also be the first statement of the constructor! A constructor cannot call another constructor of the same class and the base class. 21
50 Constructors Sup public Sup(){ public Sup(int i){ Sub public Sub(){ this( x ); public Sub(char c){ public Sub(int i){ super(i); 22
51 Constructors Sup public Sup(){ public Sup(int i){ Sup public Sup(){ super(); public Sup(int i){ super(); Sub public Sub(){ this( x ); public Sub(char c){ public Sub(int i){ super(i); Sub public Sub(){ this( x ); public Sub(char c){ super(); public Sub(int i){ super(i); Added by the compiler 22
52 Constructors Sup public Sup(){ public Sup(int i){ Sub public Sub(){ this( x ); public Sub(char c){ public Sub(int i){ super(i); Sup sup1, sup2; Sub sub1, sub2, sub3; sup1 = new Sup(); sup2 = new Sup(7); sub1 = new Sub(); sub2 = new Sub( y ); sub3 = new Sub(5); Sup public Sup(){ super(); public Sup(int i){ super(); Sub public Sub(){ this( x ); public Sub(char c){ super(); public Sub(int i){ super(i); Added by the compiler 22
53 Super keyword The super keyword is a call to the constructor of the parent class. It can also be used to call a method of the parent class: super.methoda(); This can be useful to call an overridden method. Similarly, it can be used to access data members of the parent. 23
54 super keyword example. Sup methoda(int i){ Sub methodb(){ methoda(); this.methoda(); super.methoda(); methoda(7); methoda( x ); 24
55 super keyword example. Sup methoda(int i){ Sub methodb(){ methoda(); this.methoda(); super.methoda(); methoda(7); methoda( x ); 24
56 super keyword example. Sup methoda(int i){ Sub methodb(){ methoda(); this.methoda(); super.methoda(); methoda(7); methoda( x ); 24
57 super keyword example. Sup methoda(int i){ Sub methodb(){ methoda(); this.methoda(); super.methoda(); methoda(7); methoda( x ); 24
58 super keyword example. Sup methoda(int i){ Sub methodb(){ methoda(); this.methoda(); super.methoda(); methoda(7); methoda( x ); 24
59 super keyword example. Sup methoda(int i){ Sub methodb(){ methoda(); this.methoda(); super.methoda(); methoda(7); methoda( x ); 24
60 Polymorphism Polymorphism allows a single variable to refer to objects from different subclasses in the same inheritance hierarchy For example, if Cat and Dog are subclasses of Pet, then the following statements are valid: 25
61 Polymorphism Polymorphism allows a single variable to refer to objects from different subclasses in the same inheritance hierarchy For example, if Cat and Dog are subclasses of Pet, then the following statements are valid: Pet mypet; mypet = new Dog();... mypet = new Cat(); 25
62 Creating the roster Array We can maintain our class roster using an array, combining objects from the Student, UndergraduateStudent, and GraduateStudent classes. Student roster = new Student[40];... roster[0] = new GraduateStudent(); roster[1] = new UndergraduateStudent(); roster[2] = new UndergraduateStudent();... 26
63 State of the roster Array The roster array with elements referring to instances of GraduateStudent or UndergraduateStudent classes. 27
64 State of the roster Array The roster array with elements referring to instances of GraduateStudent or UndergraduateStudent classes. 27
65 Sample Polymorphic Message To compute the course grade using the roster array, we execute 28
66 Sample Polymorphic Message To compute the course grade using the roster array, we execute for (int i = 0; i < numberofstudents; i++) { roster[i].computecoursegrade(); If roster[i] refers to a GraduateStudent, then the computecoursegrade method of the GraduateStudent class is executed. If roster[i] refers to an UndergraduateStudent, then the computecoursegrade method of the UndergraduateStudent class is executed. 28
67 Dynamic Binding At compile time, it is not known which version of a polymorphic method will get executed This is determined at run-time depending upon the class of the object This is called dynamic (late) binding Each object of a subclass is also an object of the superclass. But not vice versa! Do not confuse dynamic binding with overloaded methods. 29
68 Object Type Consider the inheritance hierarchy: Object A B An object of class B is also an object of classes A and Object. Thus we can use objects of class B wherever we can use objects of class A. The reverse is not true. A reference of type A can refer to an object of type B. However if we want to access the functionality of B on that object, we have to type cast to type B before doing that. 30
69 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); 31
70 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); 31
71 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub 31
72 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub :Sub 31
73 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub :Sub 31
74 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub :Sub 31
75 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub :Sub 31
76 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub sup :Sub 31
77 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub sup :Sub 31
78 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub sup :Sub 31
79 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub sup :Sub 31
80 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub sup :Sub 31
81 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub sup :Sub 31
82 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub sup :Sub 31
83 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub sup :Sub 31
84 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub sup :Sub 31
85 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ sub1.methodb(); sub sup :Sub 31
86 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); sub1.methodb(); Sub methodb(){ Note: sup.methodb( ) will not compile. sub sup :Sub 31
87 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); sub1.methodb(); Sub methodb(){ Note: sup.methodb( ) will not compile. sub sup :Sub 31
88 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); sub1.methodb(); Sub methodb(){ Note: sup.methodb( ) will not compile. sub sup :Sub 31
89 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ Note: sup.methodb( ) will not compile. sub1.methodb(); sub sup sub1 :Sub 31
90 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); Sub methodb(){ Note: sup.methodb( ) will not compile. sub1.methodb(); sub sup sub1 :Sub 31
91 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); sub1.methodb(); sub sup sub1 Sub methodb(){ Note: sup.methodb( ) will not compile. Casting to Sub will work, but a runtime exception (ClassCastException) will be thrown if the object is not really a Sub object. :Sub 31
92 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); sub1.methodb(); sub sup sub1 Sub methodb(){ Note: sup.methodb( ) will not compile. Casting to Sub will work, but a runtime exception (ClassCastException) will be thrown if the object is not really a Sub object. :Sub 31
93 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); sub1.methodb(); sub sup sub1 Sub methodb(){ Note: sup.methodb( ) will not compile. Casting to Sub will work, but a runtime exception (ClassCastException) will be thrown if the object is not really a Sub object. :Sub 31
94 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); sub1.methodb(); sub sup sub1 Sub methodb(){ Note: sup.methodb( ) will not compile. Casting to Sub will work, but a runtime exception (ClassCastException) will be thrown if the object is not really a Sub object. :Sub 31
95 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); sub1.methodb(); sub sup sub1 Sub methodb(){ Note: sup.methodb( ) will not compile. Casting to Sub will work, but a runtime exception (ClassCastException) will be thrown if the object is not really a Sub object. :Sub 31
96 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); sub1.methodb(); sub sup sub1 Sub methodb(){ Note: sup.methodb( ) will not compile. Casting to Sub will work, but a runtime exception (ClassCastException) will be thrown if the object is not really a Sub object. :Sub 31
97 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); sub1.methodb(); sub sup sub1 Sub methodb(){ Note: sup.methodb( ) will not compile. Casting to Sub will work, but a runtime exception (ClassCastException) will be thrown if the object is not really a Sub object. :Sub 31
98 Polymorphism example Sup Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodB(); Sub sub1 = (Sub)sup; sub1.methoda(); sub1.methodb(); sub sup sub1 Sub methodb(){ Note: sup.methodb( ) will not compile. Casting to Sub will work, but a runtime exception (ClassCastException) will be thrown if the object is not really a Sub object. :Sub 31
99 Example Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodA(); sub = (Sub)sup; sub.methoda(); Sup methoda(string[] s){ Sub methoda(int i){ sub.methoda( test ); 32
100 Example Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodA(); sub = (Sub)sup; sub.methoda(); Sup methoda(string[] s){ Sub methoda(int i){ sub.methoda( test ); 32
101 Example Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodA(); sub = (Sub)sup; sub.methoda(); Sup methoda(string[] s){ Sub methoda(int i){ sub.methoda( test ); 32
102 Example Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodA(); sub = (Sub)sup; sub.methoda(); Sup methoda(string[] s){ Sub methoda(int i){ sub.methoda( test ); 32
103 Example Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodA(); sub = (Sub)sup; sub.methoda(); Sup methoda(string[] s){ Sub methoda(int i){ sub.methoda( test ); 32
104 Example Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodA(); sub = (Sub)sup; sub.methoda(); Sup methoda(string[] s){ Sub methoda(int i){ sub.methoda( test ); 32
105 Example Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodA(); sub = (Sub)sup; sub.methoda(); Sup methoda(string[] s){ Sub methoda(int i){ sub.methoda( test ); 32
106 Example Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodA(); sub = (Sub)sup; sub.methoda(); Sup methoda(string[] s){ Sub methoda(int i){ sub.methoda( test ); 32
107 Example Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodA(); sub = (Sub)sup; sub.methoda(); Sup methoda(string[] s){ Sub methoda(int i){ sub.methoda( test ); 32
108 Example Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodA(); sub = (Sub)sup; sub.methoda(); Sup methoda(string[] s){ Sub methoda(int i){ sub.methoda( test ); 32
109 Example Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodA(); sub = (Sub)sup; sub.methoda(); Sup methoda(string[] s){ Sub methoda(int i){ sub.methoda( test ); 32
110 Example Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodA(); sub = (Sub)sup; sub.methoda(); Sup methoda(string[] s){ Sub methoda(int i){ sub.methoda( test ); 32
111 Example Sub sub = new Sub(); Sup sup; sup = sub; sup.methoda(); ((Sub)sup).methodA(); sub = (Sub)sup; sub.methoda(); Sup methoda(string[] s){ Sub methoda(int i){ sub.methoda( test ); 32
112 The instanceof Operator The instanceof operator can help us discover the class of an object at runtime. The following code counts the number of undergraduate students. new undergradcount = 0; for (int i = 0; i < numberofstudents; i++) { if ( roster[i] instanceof UndergraduateStudent ) { undergradcount++; 33
113 Abstract Superclasses and Methods When we define a superclass, we often do not need to create any instances of the superclass. Depending on whether we need to create instances of the superclass, we must define the class differently. We will study examples based on the Student superclass defined earlier. 34
114 Definition: Abstract Class An abstract class is a class defined with the modifier abstract OR that contains an abstract method OR that does not provide an implementation of an inherited abstract method An abstract method is a method with the keyword abstract, and it ends with a semicolon instead of a method body. Private methods and static methods may not be declared abstract. No instances can be created from an abstract class. 35
115 Case 1 A Student must be Undergraduate or Graduate If a student must be either an undergraduate or a graduate student, we only need instances of UndergraduateStudent or GraduateStudent. Therefore, we should define the Student class so that no instances may be created of it. 36
116 Example: Abstract classes abstract class Student { protected final static int NUM_OF_TESTS = 3; protected String name; protected int[] test; protected String coursegrade; public Student( ) { this("no Name"); public Student(String studentname) { name = studentname; test = new int[num_of_tests]; coursegrade = "****"; public String getcoursegrade( ) { return coursegrade; public String getname( ) { return name; public int gettestscore(int testnumber) { return test[testnumber-1]; public void setname(string newname) { name = newname; public void settestscore(int testnumber, int testscore) { test[testnumber-1] = testscore; 37
117 Example: Abstract classes abstract class Student { protected final static int NUM_OF_TESTS = 3; protected String name; protected int[] test; protected String coursegrade; public Student( ) { this("no Name"); public Student(String studentname) { name = studentname; test = new int[num_of_tests]; coursegrade = "****"; public String getcoursegrade( ) { return coursegrade; public String getname( ) { return name; public int gettestscore(int testnumber) { return test[testnumber-1]; public void setname(string newname) { name = newname; public void settestscore(int testnumber, int testscore) { test[testnumber-1] = testscore; class UndergraduateStudent extends Student { public void computecoursegrade() { int total = 0; for (int i = 0; i < NUM_OF_TESTS; i++) { total += test[i]; if (total / NUM_OF_TESTS >= 70) { coursegrade = "Pass"; else { coursegrade = "No Pass"; 37
118 Example: Abstract classes abstract class Student { protected final static int NUM_OF_TESTS = 3; protected String name; protected int[] test; protected String coursegrade; public Student( ) { this("no Name"); public Student(String studentname) { name = studentname; test = new int[num_of_tests]; coursegrade = "****"; public String getcoursegrade( ) { return coursegrade; public String getname( ) { return name; public int gettestscore(int testnumber) { return test[testnumber-1]; public void setname(string newname) { name = newname; public void settestscore(int testnumber, int testscore) { test[testnumber-1] = testscore; class UndergraduateStudent extends Student { public void computecoursegrade() { int total = 0; for (int i = 0; i < NUM_OF_TESTS; i++) { total += test[i]; if (total / NUM_OF_TESTS >= 70) { coursegrade = "Pass"; else { coursegrade = "No Pass"; class GraduateStudent extends Student { public void computecoursegrade() { int total = 0; for (int i = 0; i < NUM_OF_TESTS; i++) { total += test[i]; if (total / NUM_OF_TESTS >= 80) { coursegrade = "Pass"; else { coursegrade = "No Pass"; 37
119 Abstract example (contd.) Non-private members of the abstract parent class are inherited. Note: constructors are not inherited! Default constructor calls super! public class Test { public static void main(string[ ] args){ Student s; GraduateStudent g; UndergraduateStudent u; s = new Student(); g = new GraduateStudent( John ); g = new GraduateStudent(); u = new UndergraduateStudent(); System.out.println(g.getName()); System.out.println(u.getName()); 38
120 Abstract example (contd.) Non-private members of the abstract parent class are inherited. Note: constructors are not inherited! Default constructor calls super! public class Test { public static void main(string[ ] args){ Student s; GraduateStudent g; UndergraduateStudent u; Cannot instantiate abstract class. s = new Student(); g = new GraduateStudent( John ); g = new GraduateStudent(); u = new UndergraduateStudent(); System.out.println(g.getName()); System.out.println(u.getName()); 38
121 Abstract example (contd.) Non-private members of the abstract parent class are inherited. Note: constructors are not inherited! Default constructor calls super! public class Test { public static void main(string[ ] args){ Student s; GraduateStudent g; UndergraduateStudent u; Cannot instantiate abstract class. s = new Student(); g = new GraduateStudent( John ); g = new GraduateStudent(); u = new UndergraduateStudent(); System.out.println(g.getName()); System.out.println(u.getName()); Error: constructor not inherited! 38
122 Abstract example (contd.) Non-private members of the abstract parent class are inherited. Note: constructors are not inherited! Default constructor calls super! public class Test { public static void main(string[ ] args){ Student s; GraduateStudent g; UndergraduateStudent u; Cannot instantiate abstract class. s = new Student(); g = new GraduateStudent( John ); g = new GraduateStudent(); u = new UndergraduateStudent(); System.out.println(g.getName()); System.out.println(u.getName()); Error: constructor not inherited! Inherited from abstract parent class. 38
123 Case 2 Student does not have to be Undergraduate or Graduate. In this case, we may design the Student class in one of two ways. We can make the Student class instantiable. We can leave the Student class abstract and add a third subclass, OtherStudent, to handle a student who does not fall into the UndergraduateStudent or GraduateStudent categories. 39
124 Which Approach to Use? The best approach depends on the particular situation. When considering design options, we can ask ourselves which approach allows easier modification and extension. 40
125 Inheritance versus Interface The Java interface is used to share common behavior (only method headers) among the instances of different classes. Inheritance is used to share common code (including both data members and methods) among the instances of related classes. In your program designs, remember to use the Java interface to share common behavior. Use inheritance to share common code. If an entity A is a specialized form of another entity B, then model them using inheritance. Declare A as a subclass of B. 41
126 Interface vs inheritance Interface Inheritance Data members? No Yes Methods? Only headers -- no body Yes Keyword implements extends Multiple? Yes No Instantiable? No Yes (if not abstract) An interface essentially provides compliance with some desired behavior. Inheritance allows sharing of code. 42
127 Interfaces A class does not extend an interface, instead it implements an interface. Implementing implies that the class must provide the bodies for all the methods specified in the interface i.e. with the same signatures & return types Remember: GUI interfaces ActionListener 43
128 Introduction to Data Structures A data structure is a specific organization of data for efficiency or ease of coding. E.g. an array allows us to manage a large number of similar items. Many different types of data structures are used in programming. CS251 deals only with this topic! We will look at two example data structures Linked list Queue 44
129 Linked List Recall that an array s capacity is fixed once it is created or initialized. The LinkedList class in java.util used a linked list to implement a variable size list of objects. How does this work? We will study it by creating our own version of the LinkedList class which can store a list of objects of any class, in order. 45
130 Objective The linked list will allow us to Create an empty list. Add items to the end of the list. Delete items from the end of the list. Iterate through the list from beginning to end. Note: no position indexing in this version. Our linked list will be implemented as a chain of Node objects. Each Node object will have An Object data member that is the value stored at that position. A reference to the next node in the list. 46
131 The Node Class class Node { private Node next; private Object content; public void Node() { next = null; content = null; public Object getcontent(){ return content; public void setcontent(object c){ content = c; public Node getnext(){ return next; public void setnext(node nextnode){ next = nextnode; :Node next content 47
132 The LinkedList class class LinkedList { private Node head; private Node iterator; public void LinkedList() { head = null; iterator = null; public void addtohead(object c){ Node n = new Node(); n.setcontent(c); n.setnext(head); head = n; public void deletefromhead throws Exception (){ if(head== null) throw new Exception( Empty List ); else head = head.getnext(); public void getfromhead throws Exception (){ if(head== null) throw new Exception( Empty List ); else return head.getcontent(); public void startscan throws Exception (){ if(head == null) throw new Exception( Empty List ); else iterator = head; public boolean hasmore(){ if(iterator.next == null) return false; else return true; public void moveahead(){ iterator = iterator.getnext(); public Object getcurrentitem throws Exception (){ if(iterator == null) throw new Exception( No Current Item ); return iterator.getcontent(); 48
133 Example LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; list.addtohead(s); s = test3 ; list.addtohead(s); 49
134 Example list LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; list.addtohead(s); s = test3 ; list.addtohead(s); 49
135 Example list :LinkedList head iterator LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; list.addtohead(s); s = test3 ; list.addtohead(s); 49
136 Example list :LinkedList head iterator LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; list.addtohead(s); s = test3 ; list.addtohead(s); s 49
137 Example list :LinkedList head iterator test1 LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; list.addtohead(s); s = test3 ; list.addtohead(s); s 49
138 Example list :LinkedList head iterator :Node content next test1 LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; list.addtohead(s); s = test3 ; list.addtohead(s); s 49
139 Example list :LinkedList head iterator :Node content next test1 LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; list.addtohead(s); s = test3 ; list.addtohead(s); s 49
140 Example list :LinkedList head iterator :Node content next test1 LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; list.addtohead(s); s = test3 ; list.addtohead(s); s 50
141 Example list :LinkedList head iterator :Node content next test1 LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; list.addtohead(s); s = test3 ; list.addtohead(s); test2 s 50
142 Example list :LinkedList head iterator :Node content next test1 LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; list.addtohead(s); s = test3 ; list.addtohead(s); test2 s 50
143 Example list :LinkedList head iterator :Node content next test1 LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; :Node content next test2 s list.addtohead(s); s = test3 ; list.addtohead(s); 50
144 Example list :LinkedList head iterator :Node content next test1 LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; :Node content next test2 s list.addtohead(s); s = test3 ; list.addtohead(s); 50
145 Example list :LinkedList head iterator :Node content next test1 LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; :Node content next test2 s list.addtohead(s); s = test3 ; list.addtohead(s); 51
146 Example list :LinkedList head iterator :Node content next test1 LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; :Node content next test2 s list.addtohead(s); s = test3 ; list.addtohead(s); test3 51
147 Example list :LinkedList head iterator :Node content next test1 LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; :Node content next test2 s list.addtohead(s); s = test3 ; list.addtohead(s); test3 51
148 Example list :LinkedList head iterator :Node content next test1 LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; :Node content next test2 s list.addtohead(s); s = test3 ; list.addtohead(s); :Node content test3 next 51
149 Example list :LinkedList head iterator :Node content next test1 LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; :Node content next test2 s list.addtohead(s); s = test3 ; list.addtohead(s); :Node content test3 next 51
150 Example list :LinkedList head iterator :Node content next test1 :Node list.startscan(); s = (String) list.getcurrentitem(); System.out.println(s); while(list.hasmore()){ list.moveahead(); s = (String) list.getcurrentitem(); System.out.println(s); content next :Node content next test2 test3 s 52
151 Example list :LinkedList head iterator :Node content next test1 :Node list.startscan(); s = (String) list.getcurrentitem(); System.out.println(s); while(list.hasmore()){ list.moveahead(); s = (String) list.getcurrentitem(); System.out.println(s); content next :Node content next test2 test3 s 52
152 Example list :LinkedList head iterator :Node content next test1 :Node list.startscan(); s = (String) list.getcurrentitem(); System.out.println(s); while(list.hasmore()){ list.moveahead(); s = (String) list.getcurrentitem(); System.out.println(s); content next :Node content next test2 test3 s 52
153 Example list :LinkedList head iterator :Node content next test1 :Node list.startscan(); s = (String) list.getcurrentitem(); System.out.println(s); while(list.hasmore()){ list.moveahead(); s = (String) list.getcurrentitem(); System.out.println(s); content next :Node content next test2 test3 s 52
154 Example list :LinkedList head iterator :Node content next test1 :Node list.startscan(); s = (String) list.getcurrentitem(); System.out.println(s); while(list.hasmore()){ list.moveahead(); s = (String) list.getcurrentitem(); System.out.println(s); content next :Node content next test2 test3 s 52
155 Example list :LinkedList head iterator :Node content next test1 :Node list.startscan(); s = (String) list.getcurrentitem(); System.out.println(s); while(list.hasmore()){ list.moveahead(); s = (String) list.getcurrentitem(); System.out.println(s); content next :Node content next test2 test3 s 52
156 Example list :LinkedList head iterator :Node content next test1 :Node list.startscan(); s = (String) list.getcurrentitem(); System.out.println(s); while(list.hasmore()){ list.moveahead(); s = (String) list.getcurrentitem(); System.out.println(s); content next :Node content next test2 test3 s 52
157 Example list :LinkedList head iterator :Node content next test1 :Node content next test2 list.deletefromhead(); :Node content next test3 53
158 Example list :LinkedList head iterator :Node content next test1 :Node content next test2 list.deletefromhead(); :Node content next test3 53
159 Example list :LinkedList head iterator :Node content next test1 :Node content next test2 list.deletefromhead(); test3 53
160 Example list :LinkedList head iterator :Node content next test1 :Node content next test2 list.deletefromhead(); 53
161 Queue A similar Node class can be used to implement another data structure called a First-In-First-out (FIFO) queue. A FIFO queue is often used by operating systems for processes, requests, etc. In a FIFO queue, items are added at one end and deleted from the other end. For this we need to have pointers going in both directions: Node2 54
162 The Node2 Class class Node2 { private Node2 next, prev; private Object content; public void Node2() { next = null; prev = null; content = null; public Object getcontent(){ return content; public void setcontent(object c){ content = c; public Node2 getnext(){ return next; public void setnext(node2 nextnode){ next = nextnode; public Node getprev(){ return prev; public void setprev(node2 prevnode){ prev = prevnode; :Node2 next content prev 55
163 The FifoQ class class FifoQ { private Node2 head, tail; public void FifoQ() { head = null; tail = null; public void addtoq(object c){ Node2 n = new Node2(); n.setcontent(c); n.setnext(head); head.setprev(n); head = n; public void deletefromq throws Exception (){ if(tail== null) throw new Exception( Empty Queue ); if(tail.getprev() == null){ tail = null; head = null; else { tail = tail.getprev(); tail.setnext(null); 56
164 Example FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); 57
165 Example q FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); 57
166 Example q :FifoQ FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); tail head 57
167 Example q :FifoQ FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); tail head test1 s 57
168 Example q FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); :FifoQ tail head :Node2 next content prev test1 s 57
169 Example q FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); :FifoQ tail head :Node2 next content prev test1 s 57
170 Example q FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); :FifoQ tail head :Node2 next content prev test1 s 57
171 Example q FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); :FifoQ tail head :Node2 next content prev test1 s 58
172 Example q FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); :FifoQ tail head :Node2 next content prev test1 test2 s 58
173 Example q FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); :FifoQ tail head :Node2 next content prev :Node2 next content prev test1 test2 s 58
174 Example q FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); :FifoQ tail head :Node2 next content prev :Node2 next content prev test1 test2 s 58
175 Example q FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); :FifoQ tail head :Node2 next content prev :Node2 next content prev test1 test2 s 58
176 Example q FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); :FifoQ tail head :Node2 next content prev :Node2 next content prev test1 test2 59
177 Example q FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); :FifoQ tail head :Node2 next content prev :Node2 next content prev test1 test2 59
178 Example q FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); :FifoQ tail head :Node2 next content prev :Node2 next content prev test1 test2 59
179 Example q :FifoQ FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); tail head :Node2 next content prev test2 59
180 Example q :FifoQ FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); tail head :Node2 next content prev test2 60
181 Example q :FifoQ FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); tail head :Node2 next content prev test2 60
182 Example q :FifoQ FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); tail head :Node2 next content prev test2 60
183 Example q :FifoQ FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); tail head 60
184 Problem Statement Write an application that reads in a text file organized in the manner shown below and displays the final course grades.the course grades are computed differently for the undergraduate and graduate students based on the formulas listed on page 710. The input text file format is as follows: A single line is used for information on one student. Each line uses the format <Type> <Name> <Test 1> <Test 2> <Test 3> where <Type> designates either a graduate or an undergraduate student,<name> designates the student s first and last name, and <Test i> designates the ith test score. of the End of input is designated by the word END. The case letters is insignificant. 61
185 Overall Plan Tasks Read an input file Compute the course grades Print out the result Input file format: <Type> <Name> <Test 1> <Test 2> <Test 3> U John Doe G Jill Jones G Jack Smith U Mary Hines U Mick Taylor END 62
186 Development Steps We will develop this program in five steps: 1. Start with the program skeleton.define the skeleton ComputeGrades classes. 2. Implement the printresult method.define any other methods necessary to implement printresult. 3. Implement the computegrade method.define any other methods necessary to implement computegrade. 4. Implement the readdata method.define any other methods necessary to implement readdata. 5. Finalize and look for improvements. 63
187 Step 1 Design We start with a program skeleton. We will define two constructors so the programmer can create a roster of default size or the size of her choice. 64
188 Step 1 Code Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE. Directory: Chapter13/Step1 Source Files: ComputeGrades.java 65
189 Step 1 Test We include a temporary output statement inside the (currently stub) method we define. We run the test main class and verify that the methods are called correctly. 66
190 Step 2 Design We design and implement the printresult method We use the helper class OutputBox for displaying the result. for each element i in the roster array { output the name of roster[i]; output the test scores of roster[i]; output the course grade of roster[i]; skip to the next line; 67
191 Step 2 Code Directory: Chapter13/Step2 Source Files: ComputeGrades.java 68
192 Step 2 Test We verify the temporary readdata method is working correctly. This confirms that we are using the correct student classes and using their methods correctly. We verify the printresult method does indeed display the data in our desired format. 69
193 Step 3 Design 70
194 Step 3 Design We design and implement the computegrade method. 70
195 Step 3 Design We design and implement the computegrade method. The code for actually determining the course grade is embedded in individual student classes 70
196 Step 3 Design We design and implement the computegrade method. The code for actually determining the course grade is embedded in individual student classes So the code to add to the ComputeGrades class is very simplistic. 70
197 Step 3 Design We design and implement the computegrade method. The code for actually determining the course grade is embedded in individual student classes So the code to add to the ComputeGrades class is very simplistic. This is a direct benefit of using polymorphism effectively. 70
198 Step 3 Code Directory: Chapter13/Step3 Source Files: ComputeGrades.java 71
199 Step 3 Test We will repeat the same test routines from Step 2. Instead of seeing four asterisks, we should be seeing the correct grades. We test both the passing and not passing test scores. 72
200 Step 4 Design We design and implement the core functionality of the program the readdata method We can express its logic as get the filename from the user; if (the filename is provided) read in data and build the roster array; else output an error message; 73
201 The buildroster Method set bufreader for input; while (!done ) { line = get next line; if (line is END) { done = true; else { student = createstudent( line ); if (student!= null) { roster[studentcount] = student; //add to roster studentcount++; 74
202 The buildroster Method The logic of the workhorse private method buildroster is as follows: set bufreader for input; while (!done ) { line = get next line; if (line is END) { done = true; else { student = createstudent( line ); if (student!= null) { roster[studentcount] = student; //add to roster studentcount++; 74
203 The createstudent Method StringTokenizer parser = new StringTokenizer( line ); String type; try { type = parser.nexttoken(); if (type.equals(under_grad) type.equals(grad)) { student = newstudentwithdata(type, parser); else { //invalid type is encountered student = null; catch (NoSuchElementException e) { //no token student = null; return student; 75
204 The createstudent Method We use the StringTokenizer class to break down items in a single line of input StringTokenizer parser = new StringTokenizer( line ); String type; try { type = parser.nexttoken(); if (type.equals(under_grad) type.equals(grad)) { student = newstudentwithdata(type, parser); else { //invalid type is encountered student = null; catch (NoSuchElementException e) { //no token student = null; return student; 75
205 Step 4 Code Directory: Chapter13/Step4 Source Files: ComputeGrades.java 76
206 Step 4 Test 77
207 Step 4 Test We run through a more complete testing routine in this step.we need to run the program for various types of input files. Some of the possible file contents are as follows: 77
Announcements. Final exam. Course evaluations. Saturday Dec 15 10:20 am -- 12:20 pm Room: TBA
Announcements Final exam Saturday Dec 15 10:20 am -- 12:20 pm Room: TBA Course evaluations Wednesday November 28th Need volunteer to collect evaluations and deliver them to LWSN. 1 Chapter 13 Inheritance
More informationWeek 11. Abstract Data Types. CS 180 Sunil Prabhakar Department of Computer Science Purdue University
Week 11 Abstract Data Types CS 180 Sunil Prabhakar Department of Computer Science Purdue University Unknown input size Consider a program that has to read in a large number of names from input and print
More informationInheritance and Polymorphism
Inheritance and Polymorphism Recitation 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University Project 5 Due Wed, Oct. 22 at 10 pm. All questions on the class newsgroup. Make use of lab
More informationChapter 10. Further Abstraction Techniques
Chapter 10 Further Abstraction Techniques In the previous chapter, we saw how Java checks the usage of methods. We also saw that if the method is not defined in the superclass, the compiler will not work.
More informationChapter 4. Inheritance
Chapter 4 Inheritance CSC 113 King Saud University College of Computer and Information Sciences Department of Computer Science Dr. S. HAMMAMI Objectives In In this this chapter you you will will learn
More informationCS-202 Introduction to Object Oriented Programming
CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction
More informationPolymorphism. Chapter 4. CSC 113 King Saud University College of Computer and Information Sciences Department of Computer Science. Dr. S.
Chapter 4 Polymorphm CSC 113 King Saud University College Computer and Information Sciences Department Computer Science Objectives After you have read and studied th chapter, you should be able to Write
More informationCISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.
CISC-124 20180215 These notes are intended to summarize and clarify some of the topics that have been covered recently in class. The posted code samples also have extensive explanations of the material.
More informationWhat is Inheritance?
Inheritance 1 Agenda What is and Why Inheritance? How to derive a sub-class? Object class Constructor calling chain super keyword Overriding methods (most important) Hiding methods Hiding fields Type casting
More informationJava Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.
Java Inheritance Written by John Bell for CS 342, Spring 2018 Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources. Review Which of the following is true? A. Java classes may either
More informationHAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.
HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all
More informationJava Object Oriented Design. CSC207 Fall 2014
Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code
More information1 Shyam sir JAVA Notes
1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write
More informationOOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.
OOPs Concepts 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8. Type Casting Let us discuss them in detail: 1. Data Hiding: Every
More informationInheritance (continued) Inheritance
Objectives Chapter 11 Inheritance and Polymorphism Learn about inheritance Learn about subclasses and superclasses Explore how to override the methods of a superclass Examine how constructors of superclasses
More informationLecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University
Lecture 3 COMP1006/1406 (the Java course) Summer 2014 M. Jason Hinek Carleton University today s agenda assignments 1 (graded) & 2 3 (available now) & 4 (tomorrow) a quick look back primitive data types
More informationECE 122. Engineering Problem Solving with Java
ECE 122 Engineering Problem Solving with Java Lecture 22 Polymorphism using Interfaces Overview Problem: Can we delay decisions regarding which method to use until run time? Polymorphism Different methods
More informationInheritance, Polymorphism, and Interfaces
Inheritance, Polymorphism, and Interfaces Chapter 8 Inheritance Basics (ch.8 idea) Inheritance allows programmer to define a general superclass with certain properties (methods, fields/member variables)
More informationUser Defined Classes Part 2. CS 180 Sunil Prabhakar Department of Computer Science Purdue University
User Defined Classes Part 2 CS 180 Sunil Prabhakar Department of Computer Science Purdue University Class vs. Instance methods n Compare the Math and String class methods that we have used: Math.pow(2,3);
More informationCOMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code
COMPUTER SCIENCE DEPARTMENT PICNIC Welcome to the 2016-2017 Academic year! Meet your faculty, department staff, and fellow students in a social setting. Food and drink will be provided. When: Saturday,
More informationChapter 5. Inheritance
Chapter 5 Inheritance Objectives Know the difference between Inheritance and aggregation Understand how inheritance is done in Java Learn polymorphism through Method Overriding Learn the keywords : super
More informationAdvanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II
Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Mahmoud El-Gayyar elgayyar@ci.suez.edu.eg Ad hoc-polymorphism Outline Method overloading Sub-type Polymorphism Method overriding Dynamic
More informationCREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed
CREATED BY: Muhammad Bilal Arslan Ahmad Shaad JAVA Chapter No 5 Instructor: Muhammad Naveed Muhammad Bilal Arslan Ahmad Shaad Chapter No 5 Object Oriented Programming Q: Explain subclass and inheritance?
More informationInheritance (Outsource: )
(Outsource: 9-12 9-14) is a way to form new classes using classes that have already been defined. The new classes, known as derived classes, inherit attributes and behavior of the pre-existing classes,
More informationPractice for Chapter 11
Practice for Chapter 11 MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) Object-oriented programming allows you to derive new classes from existing
More informationCS260 Intro to Java & Android 03.Java Language Basics
03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance
More informationProgramming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017
Programming Language Concepts Object-Oriented Programming Janyl Jumadinova 28 February, 2017 Three Properties of Object-Oriented Languages: Encapsulation Inheritance Dynamic method binding (polymorphism)
More informationDay 4. COMP1006/1406 Summer M. Jason Hinek Carleton University
Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information
More informationChapter 5 Object-Oriented Programming
Chapter 5 Object-Oriented Programming Develop code that implements tight encapsulation, loose coupling, and high cohesion Develop code that demonstrates the use of polymorphism Develop code that declares
More informationCS 251 Intermediate Programming Inheritance
CS 251 Intermediate Programming Inheritance Brooke Chenoweth University of New Mexico Spring 2018 Inheritance We don t inherit the earth from our parents, We only borrow it from our children. What is inheritance?
More information25. Generic Programming
25. Generic Programming Java Fall 2009 Instructor: Dr. Masoud Yaghini Generic Programming Outline Polymorphism and Generic Programming Casting Objects and the instanceof Operator The protected Data and
More informationImplements vs. Extends When Defining a Class
Implements vs. Extends When Defining a Class implements: Keyword followed by the name of an INTERFACE Interfaces only have method PROTOTYPES You CANNOT create on object of an interface type extends: Keyword
More informationInheritance and Polymorphism
Inheritance and Polymorphism Dr. M. G. Abbas Malik Assistant Professor Faculty of Computing and IT (North Jeddah Branch) King Abdulaziz University, Jeddah, KSA mgmalik@kau.edu.sa www.sanlp.org/malik/cpit305/ap.html
More informationClass, Variable, Constructor, Object, Method Questions
Class, Variable, Constructor, Object, Method Questions http://www.wideskills.com/java-interview-questions/java-classes-andobjects-interview-questions https://www.careerride.com/java-objects-classes-methods.aspx
More informationSuper-Classes and sub-classes
Super-Classes and sub-classes Subclasses. Overriding Methods Subclass Constructors Inheritance Hierarchies Polymorphism Casting 1 Subclasses: Often you want to write a class that is a special case of an
More informationHAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.
HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all
More informationInheritance and object compatibility
Inheritance and object compatibility Object type compatibility An instance of a subclass can be used instead of an instance of the superclass, but not the other way around Examples: reference/pointer can
More informationDay 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University
Day 3 COMP 1006/1406A Summer 2016 M. Jason Hinek Carleton University today s agenda assignments 1 was due before class 2 is posted (be sure to read early!) a quick look back testing test cases for arrays
More informationMore Relationships Between Classes
More Relationships Between Classes Inheritance: passing down states and behaviors from the parents to their children Interfaces: grouping the methods, which belongs to some classes, as an interface to
More informationChapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,
Chapter 11 Inheritance and Polymorphism 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the best way to design
More informationObject Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming
Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in
More informationLecture 4: Extending Classes. Concept
Lecture 4: Extending Classes Concept Inheritance: you can create new classes that are built on existing classes. Through the way of inheritance, you can reuse the existing class s methods and fields, and
More informationAbstract Classes and Interfaces
Abstract Classes and Interfaces Reading: Reges and Stepp: 9.5 9.6 CSC216: Programming Concepts Sarah Heckman 1 Abstract Classes A Java class that cannot be instantiated, but instead serves as a superclass
More informationContents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance
Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass
More informationProgramming II (CS300)
1 Programming II (CS300) Chapter 05: Inheritance and Interfaces MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Inheritance and Interfaces 2 Introduction Inheritance and Class Hierarchy Polymorphism Abstract Classes
More informationJAVA MOCK TEST JAVA MOCK TEST II
http://www.tutorialspoint.com JAVA MOCK TEST Copyright tutorialspoint.com This section presents you various set of Mock Tests related to Java Framework. You can download these sample mock tests at your
More informationInheritance -- Introduction
Inheritance -- Introduction Another fundamental object-oriented technique is called inheritance, which, when used correctly, supports reuse and enhances software designs Chapter 8 focuses on: the concept
More information8. Polymorphism and Inheritance
8. Polymorphism and Inheritance Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich http://seal.ifi.uzh.ch/info1 Objectives Describe polymorphism and inheritance in general Define interfaces
More informationDistributed Systems Recitation 1. Tamim Jabban
15-440 Distributed Systems Recitation 1 Tamim Jabban Office Hours Office 1004 Tuesday: 9:30-11:59 AM Thursday: 10:30-11:59 AM Appointment: send an e-mail Open door policy Java: Object Oriented Programming
More informationThe software crisis. code reuse: The practice of writing program code once and using it in many contexts.
Inheritance The software crisis software engineering: The practice of conceptualizing, designing, developing, documenting, and testing largescale computer programs. Large-scale projects face many issues:
More informationBig software. code reuse: The practice of writing program code once and using it in many contexts.
Inheritance Big software software engineering: The practice of conceptualizing, designing, developing, documenting, and testing largescale computer programs. Large-scale projects face many issues: getting
More informationDistributed Systems Recitation 1. Tamim Jabban
15-440 Distributed Systems Recitation 1 Tamim Jabban Office Hours Office 1004 Sunday, Tuesday: 9:30-11:59 AM Appointment: send an e-mail Open door policy Java: Object Oriented Programming A programming
More informationProgramming in C# Inheritance and Polymorphism
Programming in C# Inheritance and Polymorphism C# Classes Classes are used to accomplish: Modularity: Scope for global (static) methods Blueprints for generating objects or instances: Per instance data
More informationArgument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.
Local Variable Initialization Unlike instance vars, local vars must be initialized before they can be used. Eg. void mymethod() { int foo = 42; int bar; bar = bar + 1; //compile error bar = 99; bar = bar
More informationOverview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008
Overview Lecture 7: Inheritance and GUIs Written by: Daniel Dalevi Inheritance Subclasses and superclasses Java keywords Interfaces and inheritance The JComponent class Casting The cosmic superclass Object
More informationPolymorphism and Inheritance
Walter Savitch Frank M. Carrano Polymorphism and Inheritance Chapter 8 Objectives Describe polymorphism and inheritance in general Define interfaces to specify methods Describe dynamic binding Define and
More informationCMSC 132: Object-Oriented Programming II. Inheritance
CMSC 132: Object-Oriented Programming II Inheritance 1 Mustang vs Model T Ford Mustang Ford Model T 2 Interior: Mustang vs Model T 3 Frame: Mustang vs Model T Mustang Model T 4 Compaq: old and new Price:
More informationCS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)
CS/B.TECH/CSE(New)/SEM-5/CS-504D/2013-14 2013 OBJECT ORIENTED PROGRAMMING Time Allotted : 3 Hours Full Marks : 70 The figures in the margin indicate full marks. Candidates are required to give their answers
More informationMore On inheritance. What you can do in subclass regarding methods:
More On inheritance What you can do in subclass regarding methods: The inherited methods can be used directly as they are. You can write a new static method in the subclass that has the same signature
More informationIslamic University of Gaza Faculty of Engineering Computer Engineering Department
Student Mark Islamic University of Gaza Faculty of Engineering Computer Engineering Department Question # 1 / 18 Question # / 1 Total ( 0 ) Student Information ID Name Answer keys Sector A B C D E A B
More informationVIRTUAL FUNCTIONS Chapter 10
1 VIRTUAL FUNCTIONS Chapter 10 OBJECTIVES Polymorphism in C++ Pointers to derived classes Important point on inheritance Introduction to virtual functions Virtual destructors More about virtual functions
More informationAP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS
AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this
More informationExercise: Singleton 1
Exercise: Singleton 1 In some situations, you may create the only instance of the class. 1 class mysingleton { 2 3 // Will be ready as soon as the class is loaded. 4 private static mysingleton Instance
More informationOutline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring
Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,
More informationGraphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub
Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java
More informationInheritance and Interfaces
Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical
More informationChapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber
Chapter 10 Inheritance and Polymorphism Dr. Hikmat Jaber 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the
More informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationJava Magistère BFA
Java 101 - Magistère BFA Lesson 3: Object Oriented Programming in Java Stéphane Airiau Université Paris-Dauphine Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 1 Goal : Thou Shalt
More informationCS 180 Final Exam Review 12/(11, 12)/08
CS 180 Final Exam Review 12/(11, 12)/08 Announcements Final Exam Thursday, 18 th December, 10:20 am 12:20 pm in PHYS 112 Format 30 multiple choice questions 5 programming questions More stress on topics
More informationCSC207H: Software Design. Java + OOP. CSC207 Winter 2018
Java + OOP CSC207 Winter 2018 1 Why OOP? Modularity: code can be written and maintained separately, and easily passed around the system Information-hiding: internal representation hidden from the outside
More informationA base class (superclass or parent class) defines some generic behavior. A derived class (subclass or child class) can extend the base class.
Inheritance A base class (superclass or parent class) defines some generic behavior. A derived class (subclass or child class) can extend the base class. A subclass inherits all of the functionality of
More informationStarting Out with Java: From Control Structures Through Objects Sixth Edition
Starting Out with Java: From Control Structures Through Objects Sixth Edition Chapter 10 Inheritance Chapter Topics (1 of 2) 10.1 What Is Inheritance? 10.2 Calling the Superclass Constructor 10.3 Overriding
More informationCMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.
CMSC131 Inheritance Object When we talked about Object, I mentioned that all Java classes are "built" on top of that. This came up when talking about the Java standard equals operator: boolean equals(object
More informationLecture Notes Chapter #9_b Inheritance & Polymorphism
Lecture Notes Chapter #9_b Inheritance & Polymorphism Inheritance results from deriving new classes from existing classes Root Class all java classes are derived from the java.lang.object class GeometricObject1
More informationCSC207H: Software Design. Java + OOP. CSC207 Winter 2018
Java + OOP CSC207 Winter 2018 1 Why OOP? Modularity: code can be written and maintained separately, and easily passed around the system Information-hiding: internal representation hidden from the outside
More informationInheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L
Inheritance Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 9.4 1 Inheritance Inheritance allows a software developer to derive
More informationInheritance (Part 5) Odds and ends
Inheritance (Part 5) Odds and ends 1 Static Methods and Inheritance there is a significant difference between calling a static method and calling a non-static method when dealing with inheritance there
More informationInheritance & Abstract Classes Fall 2018 Margaret Reid-Miller
Inheritance & Abstract Classes 15-121 Margaret Reid-Miller Today Today: Finish circular queues Exercise: Reverse queue values Inheritance Abstract Classes Clone 15-121 (Reid-Miller) 2 Object Oriented Programming
More informationInformatik II (D-ITET) Tutorial 6
Informatik II (D-ITET) Tutorial 6 TA: Marian George, E-mail: marian.george@inf.ethz.ch Distributed Systems Group, ETH Zürich Exercise Sheet 5: Solutions and Remarks Variables & Methods beginwithlowercase,
More informationInheritance and Polymorphism
Object Oriented Programming Designed and Presented by Dr. Ayman Elshenawy Elsefy Dept. of Systems & Computer Eng.. Al-Azhar University Website: eaymanelshenawy.wordpress.com Email : eaymanelshenawy@azhar.edu.eg
More informationComp 249 Programming Methodology
Comp 249 Programming Methodology Chapter 7 - Inheritance Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal, Canada These slides has been extracted,
More informationInheritance. Notes Chapter 6 and AJ Chapters 7 and 8
Inheritance Notes Chapter 6 and AJ Chapters 7 and 8 1 Inheritance you know a lot about an object by knowing its class for example what is a Komondor? http://en.wikipedia.org/wiki/file:komondor_delvin.jpg
More informationLecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting
Lecture 36: Cloning Last time: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting Today: 1. Project #7 assigned 2. equals reconsidered 3. Copying and cloning 4. Composition 11/27/2006
More informationArrays Classes & Methods, Inheritance
Course Name: Advanced Java Lecture 4 Topics to be covered Arrays Classes & Methods, Inheritance INTRODUCTION TO ARRAYS The following variable declarations each allocate enough storage to hold one value
More informationFirst IS-A Relationship: Inheritance
First IS-A Relationship: Inheritance The relationships among Java classes form class hierarchy. We can define new classes by inheriting commonly used states and behaviors from predefined classes. A class
More informationMore About Objects. Zheng-Liang Lu Java Programming 255 / 282
More About Objects Inheritance: passing down states and behaviors from the parents to their children. Interfaces: requiring objects for the demanding methods which are exposed to the outside world. Polymorphism
More informationCS Programming I: Inheritance
CS 200 - Programming I: Inheritance Marc Renault Department of Computer Sciences University of Wisconsin Madison Fall 2017 TopHat Sec 3 (PM) Join Code: 719946 TopHat Sec 4 (AM) Join Code: 891624 Inheritance
More informationThis week. Tools we will use in making our Data Structure classes: Generic Types Inheritance Abstract Classes and Interfaces
This week Tools we will use in making our Data Structure classes: Generic Types Inheritance Abstract Classes and Interfaces This is a lot of material but we'll be working with these tools the whole semester
More informationObject Oriented Design. Object-Oriented Design. Inheritance & Polymorphism. Class Hierarchy. Goals Robustness Adaptability Flexible code reuse
Object-Oriented Design Object Oriented Design Goals Robustness Adaptability Flexible code reuse Principles Abstraction Encapsulation Modularity March 2005 Object Oriented Design 1 March 2005 Object Oriented
More informationCSEN401 Computer Programming Lab. Topics: Object Oriented Features: Abstraction and Polymorphism
CSEN401 Computer Programming Lab Topics: Object Oriented Features: Abstraction and Polymorphism Prof. Dr. Slim Abdennadher 23.2.2015 c S. Abdennadher 1 Object-Oriented Paradigm: Features Easily remembered
More informationINHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U
C A N A D I A N I N T E R N A T I O N A L S C H O O L O F H O N G K O N G INHERITANCE & POLYMORPHISM P2 LESSON 12 P2 LESSON 12.1 INTRODUCTION inheritance: OOP allows a programmer to define new classes
More informationInformatik II. Tutorial 6. Mihai Bâce Mihai Bâce. April 5,
Informatik II Tutorial 6 Mihai Bâce mihai.bace@inf.ethz.ch 05.04.2017 Mihai Bâce April 5, 2017 1 Overview Debriefing Exercise 5 Briefing Exercise 6 Mihai Bâce April 5, 2017 2 U05 Some Hints Variables &
More informationChapter 6 Introduction to Defining Classes
Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of
More informationHAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.
HAS-A Relationship Association is a weak relationship where all objects have their own lifetime and there is no ownership. For example, teacher student; doctor patient. If A uses B, then it is an aggregation,
More informationCLASS DESIGN. Objectives MODULE 4
MODULE 4 CLASS DESIGN Objectives > After completing this lesson, you should be able to do the following: Use access levels: private, protected, default, and public. Override methods Overload constructors
More informationCS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University
CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Inheritance Three main programming mechanisms that constitute object-oriented programming (OOP) Encapsulation
More informationObject Oriented Programming. Java-Lecture 11 Polymorphism
Object Oriented Programming Java-Lecture 11 Polymorphism Abstract Classes and Methods There will be a situation where you want to develop a design of a class which is common to many classes. Abstract class
More informationCS 112 Programming 2. Lecture 06. Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism
CS 112 Programming 2 Lecture 06 Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism rights reserved. 2 Motivation Suppose you want to define classes to model circles, rectangles, and
More informationTopic 7: Inheritance. Reading: JBD Sections CMPS 12A Winter 2009 UCSC
Topic 7: Inheritance Reading: JBD Sections 7.1-7.6 1 A Quick Review of Objects and Classes! An object is an abstraction that models some thing or process! Examples of objects:! Students, Teachers, Classes,
More information