Announcements. Final exam. Course evaluations. Saturday Dec 15 10:20 am -- 12:20 pm Room: TBA
|
|
- Christina Beasley
- 5 years ago
- Views:
Transcription
1 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
2 Chapter 13 Inheritance and Polymorphism CS 180 Sunil Prabhakar Department of Computer Science Purdue University
3 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. 3
4 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. 4
5 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. 5
6 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 6
7 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. 7
8 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. 8
9 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(); 9
10 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"; 10
11 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"; 11
12 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 12
13 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. 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); 14
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); 14
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); 14
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); 14
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(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 14
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(); sub.methoda(i); sub.methoda(c); sup.methoda(c); overloaded Sup methoda(int i){ Sub methoda(char c){ 14
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); 14
21 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); 14
22 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){ 14
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); 14
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(); Sup methoda(int i){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 14
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(); sub.methoda(i); sub.methoda(c); sup.methoda(c); inherited Sup methoda(int i){ Sub methoda(char c){ 14
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); 14
27 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); 14
28 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){ 14
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); 14
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){ Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 14
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){ Overloaded & Auto cast Sub methoda(char c){ sub.methoda(i); sub.methoda(c); sup.methoda(c); 14
32 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); 14
33 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() 15
34 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 16
35 Inheritance and Member Accessibility We use the following visual representation of inheritance to illustrate data member accessibility. public protected private Accessible Inaccessible 17
36 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 17
37 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 17
38 The Effect of the Visibility Modifiers public protected private :Super Accessible Inaccessible :Client :Sub :Super Accessibility from a Client method 18
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. 18
40 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. 18
41 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. 18
42 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 18
43 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 18
44 Accessibility of Super from Sub public protected private Accessibility from a method of the Sub class :Super :Sub 19
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. 19
46 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. 19
47 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 19
48 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. 20
49 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 ); 21
50 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. 22
51 Constructors Sup public Sup(){ public Sup(int i){ Sub public Sub(){ this( x ); public Sub(char c){ public Sub(int i){ super(i); 23
52 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 23
53 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 23
54 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. 24
55 super keyword example. Sup methoda(int i){ Sub methodb(){ methoda(); this.methoda(); super.methoda(); methoda(7); methoda( x ); 25
56 super keyword example. Sup methoda(int i){ Sub methodb(){ methoda(); this.methoda(); super.methoda(); methoda(7); methoda( x ); 25
57 super keyword example. Sup methoda(int i){ Sub methodb(){ methoda(); this.methoda(); super.methoda(); methoda(7); methoda( x ); 25
58 super keyword example. Sup methoda(int i){ Sub methodb(){ methoda(); this.methoda(); super.methoda(); methoda(7); methoda( x ); 25
59 super keyword example. Sup methoda(int i){ Sub methodb(){ methoda(); this.methoda(); super.methoda(); methoda(7); methoda( x ); 25
60 super keyword example. Sup methoda(int i){ Sub methodb(){ methoda(); this.methoda(); super.methoda(); methoda(7); methoda( x ); 25
61 Quiz Which method is executed for each of these calls? Sup sup = new Sup(); Sub sub = new Sub(); int i=9; char c='c'; String s= test sub.methoda(); sub.methoda(i); sub.methoda(s); sup.methoda(c); Sup methoda(int i){ Sub methoda(string s){ methoda(int j){ 26
62 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: 27
63 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(); 27
64 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();... 28
65 State of the roster Array The roster array with elements referring to instances of GraduateStudent or UndergraduateStudent classes. 29
66 State of the roster Array The roster array with elements referring to instances of GraduateStudent or UndergraduateStudent classes. 29
67 Sample Polymorphic Message To compute the course grade using the roster array, we execute 30
68 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. 30
69 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. 31
70 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. 32
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(); 33
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(); 33
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 33
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 33
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 33
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 :Sub 33
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 :Sub 33
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 33
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 33
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 33
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 33
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 33
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 33
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 33
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 33
86 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 33
87 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 33
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 33
89 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 33
90 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 33
91 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 33
92 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 33
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 33
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 33
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 33
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 33
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 33
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 33
99 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 33
100 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 33
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 ); 34
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 ); 34
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 ); 34
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 ); 34
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 ); 34
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 ); 34
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 ); 34
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 ); 34
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 ); 34
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 ); 34
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 ); 34
112 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 ); 34
113 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 ); 34
114 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++; 35
115 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. 36
116 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. 37
117 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. 38
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; 39
119 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"; 39
120 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"; 39
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; s = new Student(); g = new GraduateStudent( John ); g = new GraduateStudent(); u = new UndergraduateStudent(); System.out.println(g.getName()); System.out.println(u.getName()); 40
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()); 40
123 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! 40
124 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. 40
125 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. 41
126 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. 42
127 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. 43
128 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. 44
129 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 45
130 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 46
131 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. 47
132 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. 48
133 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 49
134 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(); 50
135 Example LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; list.addtohead(s); s = test3 ; list.addtohead(s); 51
136 Example list LinkedList list; list = new LinkedList(); String s; s = test1 ; List.addToHead(s); s = test2 ; list.addtohead(s); s = test3 ; list.addtohead(s); 51
137 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); 51
138 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 51
139 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 51
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 51
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); s 51
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); s 52
143 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 52
144 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 52
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); 52
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); 52
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); 53
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); test3 53
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); test3 53
150 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 53
151 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 53
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 54
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 54
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 54
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 54
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 54
157 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 54
158 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 54
159 Example list :LinkedList head iterator :Node content next test1 :Node content next test2 list.deletefromhead(); :Node content next test3 55
160 Example list :LinkedList head iterator :Node content next test1 :Node content next test2 list.deletefromhead(); :Node content next test3 55
161 Example list :LinkedList head iterator :Node content next test1 :Node content next test2 list.deletefromhead(); test3 55
162 Example list :LinkedList head iterator :Node content next test1 :Node content next test2 list.deletefromhead(); 55
163 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 56
164 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 57
165 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); 58
166 Example FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); 59
167 Example q FifoQ q; q = new FifoQ(); String s; s = test1 ; q.addtoq(s); s = test2 ; q.addtoq(s); while(!q.isempty()) q.deletefromq(); 59
168 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 59
169 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 59
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 59
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 59
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 s 59
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 test1 s 60
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 test1 test2 s 60
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 60
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 s 60
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 s 60
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 61
179 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 61
180 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 61
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 61
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 62
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 :Node2 next content prev test2 62
184 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 62
185 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 62
186 Quiz Give two differences between interfaces and inheritance in Java. 63
187 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. 64
188 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 65
189 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. 66
190 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. 67
191 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 68
192 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. 69
193 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; 70
194 Step 2 Code Directory: Chapter13/Step2 Source Files: ComputeGrades.java 71
195 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. 72
196 Step 3 Design 73
197 Step 3 Design We design and implement the computegrade method. 73
198 Step 3 Design We design and implement the computegrade method. The code for actually determining the course grade is embedded in individual student classes 73
199 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. 73
200 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. 73
201 Step 3 Code Directory: Chapter13/Step3 Source Files: ComputeGrades.java 74
202 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. 75
203 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; 76
204 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++; 77
205 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++; 77
206 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; 78
207 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; 78
208 Step 4 Code Directory: Chapter13/Step4 Source Files: ComputeGrades.java 79
209 Step 4 Test 80
210 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: 80
Chapter 13. Inheritance and Polymorphism. CS 180 Sunil Prabhakar Department of Computer Science Purdue University
Chapter 13 Inheritance and Polymorphism CS 180 Sunil Prabhakar Department of Computer Science Purdue University Introduction Inheritance and polymorphism are key concepts of Object Oriented Programming.
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 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 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 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 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 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 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 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 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 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 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 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 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 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 informationPolymorphism. Final Exam. November 26, Method Overloading. Quick Review of Last Lecture. Overriding Methods.
Final Exam Polymorphism Time: Thursday Dec 13 @ 4:30-6:30 p.m. November 26, 2007 Location: Curtiss Hall, room 127 (classroom) ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
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 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 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 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 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 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 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 -- 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 informationAnnouncements. Final exam. Course evaluations. No classes next week. Saturday Dec 15 10:20 am -- 12:20 pm Room: TBA. Wednesday November 28th
Announcements Final exam Saturday Dec 15 10:20 am -- 12:20 pm Room: TBA Course evaluations Wednesday November 28th No classes next week no lectures, labs, or recitations Happy Thanksgiving! 1 Generics
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 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 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 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 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 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 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 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 informationRules and syntax for inheritance. The boring stuff
Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for
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 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 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 informationUser Defined Classes. CS 180 Sunil Prabhakar Department of Computer Science Purdue University
User Defined Classes CS 180 Sunil Prabhakar Department of Computer Science Purdue University Announcements Register for Piazza. Deleted post accidentally -- sorry. Direct Project questions to responsible
More informationComputer Science II (20073) Week 1: Review and Inheritance
Computer Science II 4003-232-01 (20073) Week 1: Review and Inheritance Richard Zanibbi Rochester Institute of Technology Review of CS-I Hardware and Software Hardware Physical devices in a computer system
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 informationCSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community
CSCI-12 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community http://csc.cs.rit.edu 1. Provide a detailed explanation of what the following code does: 1 public boolean checkstring
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 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 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 informationJava Fundamentals (II)
Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class
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 informationProgramming Exercise 14: Inheritance and Polymorphism
Programming Exercise 14: Inheritance and Polymorphism Purpose: Gain experience in extending a base class and overriding some of its methods. Background readings from textbook: Liang, Sections 11.1-11.5.
More informationLecture 10. Overriding & Casting About
Lecture 10 Overriding & Casting About Announcements for This Lecture Readings Sections 4.2, 4.3 Prelim, March 8 th 7:30-9:30 Material up to next Tuesday Sample prelims from past years on course web page
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 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 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 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 informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 20, 2014 Abstract
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 information