BM214E Object Oriented Programming Lecture 11
|
|
- Chester Cole
- 5 years ago
- Views:
Transcription
1 BM214E Oriented Programming Lecture 11
2 Interfaces & Polymorphism (continued)
3 Mini-review References: Pointers to objects. Include many of the classic confusing things about pointers! Inheritance: defined with keyword "extends". Subclasses inherit all of the fields and methods of the parent class Define subclasses in their own file Arrays are objects which require a reference Watch[] watcharray = new Watch[10]; For the most part avoid static. Creating a (reference variable vs creating an instance) TetrisBlock tb; tb = new TetrisBlock();
4 We ve already seen one use of interfaces public class P1Constants { public static final int FEETPERMILE = 5280; public class SomeOtherClass {... public int convertfeet2miles(int feet) { return feet * P1Constants.FEETPERMILE;...
5 We ve already seen one use of interfaces public interface P1Constants { final int FEETPERMILE = 5280; public class SomeOtherClass implements P1Constants {... public int convertfeet2miles(int feet) { return feet * FEETPERMILE;...
6 But the key feature... I have this structure Aquatic LandBased Goldfish Shark Dog Cat Giraffe But I want some of the animals to be Pets?
7 Pets will have names! public interface Pet { public String getname(); public void setname(string name); Note: We don't define the variable name
8 So now if I want a dog to be a pet: class Dog implements Pet { private String name; /* Plus other fields */ public String getname() { return name; public void setname(string name) { this.name = name; /* Plus other methods */
9 More Polymorphism
10 In Our Last Episode... Recall last lecture s discussion of polymorphism. This concept is a KEY feature of any object oriented language, not just Java. It is imperative that you understand how it works. Let us review.
11 Recall class { public void move ( ) { ( I am an animal and I am moving. ); // of class extends { public void move( ) { ( Swim, swim, swim, swim! ); // of class Dog extends { public void move ( ) { ( Run, scratch, walk, run ); public void bark ( ){ ( Arf Arf ); // of Dog class Bird extends { public void move( ) { ( Flap, flap, flap again ); // of Bird
12 Recall class Driver { public static void main (String[ ] argv) { [ ] animalarray = new [3]; int iindex; animalarray[0] = new Bird( ); animalarray[1] = new Dog( ); animalarray[2] = new ( ); for (iindex=0; iindex < animalarray.length; iindex++) { animalarray[iindex].move( ); // of for // of main // of Driver Output: Flap, flap, flap again Run, scratch, walk, run Swim, swim, swim, swim! We also noted that we could use polymorphism to hold an array of animals, and employ dynamic binding to invoke specific behaviors.
13 And so... Let s review the creation of an object, using a slightly more complex class example class { public int numlegs; public static int total = 0; public ; This may not be the best design. Don t forget this is an academic exercise. We re doing this for a reason. public (int numlegs){ this.numlegs = numlegs; strtype = ; total++; public void move ( ) { ( I am an animal and am moving. ); public String { return strtype + with + numlegs + legs. ; // of This time, we have instance and class variables. The int total is a population counter. The int numlegs records the number of legs for the animal. The String strtype describes the animal.
14 And so... Let s review the creation of an object, using a slightly more complex class example class { public int numlegs; public static int total = 0; private ; The move() method is the same as before. We ve added a constructor and a simple. public (int numlegs){ this.numlegs = numlegs; strtype = ; total++; public void move ( ) { ( I am an animal and am moving. ); public String { return strtype + with + numlegs + legs. ; // of In a perfect world, we d have room on the slides for the accessors and modifiers.
15 And also... class extends { public (int numlegs){ super(numlegs); strtype = ; public void move( ) { ( Swim, swim, swim, swim! ); // of The class is very much the same. We just add a new constructor, which invokes the parent constructor, and then corrects the strtype assignment.
16 And also... class Bird extends { public Bird(int numlegs){ super (numlegs); strtype = Bird ; public void move( ) { ( Flap, flap, flap again ); // of Bird Same story with the Bird class. We added a new constructor, and set the type appropriately.
17 And also... class Dog extends { public Dog(int numlegs){ super (numlegs); strtype = Dog ; public void move ( ) { ( Run, scratch, walk, run ); public void bark ( ){ ( Arf Arf ); // of Dog Same story with the Dog class. We added a new constructor, and set the type appropriately.
18 And Finally... class Driver { public static void main (String[ ] argv) { [ ] animalarray = new [3]; int iindex; animalarray[0] = new Bird(2); animalarray[1] = new (0); animalarray[2] = new Dog(3); for (i=0; i < animalarray.length; i++) { (animalarray[i].); animalarray[i].move( ); // of for ( Total Count: +.total); // of main // of Driver We also revise our Driver class, passing in appropriate values to the constructors. (We happen to have a three-legged dog.)
19 class { public int numlegs; public static int total = 0; private ; public (int numlegs){ this.numlegs = numlegs; strtype = ; total++; public void move ( ) { ( I am an animal and am moving. ); public String { return strtype + with + numlegs + legs. ; // of class Driver { public static void main (String[ ] argv) { [ ] animalarray = new [3]; int iindex; animalarray[0] = new Bird(2); animalarray[1] = new (0); animalarray[2] = new Dog(3); for (i=0; i < animalarray.length; i++) { (animalarray[i].); animalarray[i].move( ); // of for // of main // of Driver What Happens? class extends { public (int numlegs){ super(numlegs); strtype = ; public void move( ) { ( Swim, swim, swim, swim! ); // of class Dog extends { public Dog(int numlegs){ super (numlegs); strtype = Dog ; public void move ( ) { ( Run, scratch, walk, run ); public void bark ( ){ ( Arf Arf ); // of Dog class Bird extends { public Bird(int numlegs){ super (numlegs); strtype = Bird ; public void move( ) { ( Flap, flap, flap again ); // of Bird If we run the Driver, what happens? Moreover, WHY does it happen?
20 A Look At Memory We intend to take a close look at these objects in memory. But before we do that, we have to condense what we ve written. We ll need to agree on some symbols and a notation system. class { public int numlegs; public static int total; private ; public (int numlegs){ this.numlegs = numlegs; strtype = ; public void move ( ) { ( I am an animal and am moving. ); public String { return strtype + with + numlegs + legs. ; // of int numlegs We ll represent instances in memory as a box. We ll have a little room for the variables, and a few key methods.
21 A Look At Memory We intend to take a close look at these objects in memory. But before we do that, we have to condense what we ve written. We ll need to agree on some symbols and a notation system. class { public int numlegs; public static int total; private ; public (int numlegs){ this.numlegs = numlegs; strtype = ; public void move ( ) { ( I am an animal and am moving. ); public String { return strtype + with + numlegs + legs. ; // of int numlegs In future classes, you ll learn about UML diagrams. But for now, it s all boxes and arrows. Since an inherits from (remember IS-A relationships are specified by inheritance), we also draw an box.
22 A Look At Memory class { public int numlegs; public static int total; private ; Now, a is more complex. It inherits from which extends. public (int numlegs){ this.numlegs = numlegs; strtype = ; public void move ( ) { ( I am an animal and am moving. ); public String { return strtype + with + numlegs + legs. ; // of class extends { public (int numlegs){ super(numlegs); strtype = ; public void move( ) { ( Swim, swim, swim, swim! ); // of int numlegs This whole area is a object in memory. Since a IS-A, and an IS-A, we draw all three boxes to express one object
23 A Look At Memory Thus, if we make a instance, we have a reference pointing to this block of memory that we ve drawn. ftemp; ftemp = new (0); ftemp int numlegs = 0 By convention, we will have the reference point to a particular portion of the block of memory, even though the entire block is one object. Since our reference is a type, our arrow enters at the portion of the object in memory.
24 Recall Our Creation Timeline Remember that a call to the (int) constructor involves an explicit (int) constructor call. Even if we did not have this explicit call, Java would implicitly call the parent class constructor, just as it implicitly makes an when the (int) constructor is invoked from the (int) constructor int numlegs = 0 int numlegs = 0 int numlegs = 0 ftemp = new (0); To make a, Java must first make an. To make an, Java must first make an. ftemp
25 Wow. Notice something else. Since all are types, we can have an reference pointing to this block of memory. otemp; otemp = new (0); int numlegs = 0 A single instance otemp We adjust where the reference enters the block of memory, that that it reflects the reference type.
26 Ahh. So we can just make new reference types and have them point into our block at a different locations. By twiddling the reference into our block of memory, we can polymorph the object. atemp; atemp = new (0); atemp int numlegs = 0 We adjust where reference points, so that it reflects its type.
27 Hey, Cool int numlegs = 3 ref That s a simple example of polymorphism.
28 Hey, Cool int numlegs = 3 ref That s a simple example of polymorphism.
29 Hey, Cool It s the same object in memory. We just change the reference type pointing to it. int numlegs = 3 ref That s a simple example of polymorphism.
30 Polymorphism Many forms int numlegs = 3 One object <type> ref Literally, polymorphism means Many forms So for us we take it to imply, "One object; many forms
31 Thus So we have three box groupings that represent arbitrary instances of, Dog and Bird, pointed to by any appropriate reference type. int numlegs = 0 int numlegs = 3 Dog bark(); int numlegs = 2 Bird ftemp dtemp btemp ftemp = new (0); Dog dtemp = new Dog(3); Bird btemp = new Bird(2);
32 class { public int numlegs; public static int total = 0; private ; public (int numlegs){ this.numlegs = numlegs; strtype = ; total++; public void move ( ) { ( I am an animal and am moving. ); public String { return strtype + with + numlegs + legs. ; // of class Bird extends { public Bird(int numlegs){ super (numlegs); strtype = Bird ; public void move( ) { ( Flap, flap, flap again ); // of Bird class extends { public (int numlegs){ super(numlegs); strtype = ; public void move( ) { ( Swim, swim, swim, swim! ); // of Recall class Dog extends { public Dog(int numlegs){ super (numlegs); strtype = Dog ; public void move ( ) { ( Run, scratch, walk, run ); public void bark ( ){ ( Arf Arf ); // of Dog So we figured out how to represent inheritance in memory. Now recall that we also had our classes point to a String literal describing the type. A String literal is, well, literally a String. It s something in quotes in your source code. Literally what s there.
33 The Constant Pool atemp; atemp = new Bird(2); atemp int numlegs = 2 Bird Constant Pool Bird Dog There s an area of the Java Virtual Machine called the Constant Pool. It s a special area to hold declared constants (final variables), since they cannot be changed. As it turns out, this is where String literals are placed.
34 The Constant Pool atemp; atemp = new Bird(2); atemp int numlegs = 2 Bird Constant Pool Bird Dog Since Strings are s, and are addressed through references, the strtype variable in the class points to one of these literals in the Constant Pool.
35 The Constant Pool atemp; atemp = new Bird(2); atemp int numlegs = 2 Bird Constant Pool Bird Dog Note that this is different for primitive instance variables. Primitives are not references. So we just write the value right next to the field
36 In Fact... atemp; atemp = new Bird(2); atemp int numlegs = 2 Bird Constant Pool String String Bird String String Dog In fact, the also inherits from. So we could even draw the Constant Pool as a collection of objects with inheritance. But this is getting too complicated.
37 int numlegs = 2 Bird All of the objects created by our Driver class have unique values (numlegs) and unique references. So, we ll abstract away most of the details, and just note that objects in Java are handled through references. Constant Pool Bird Dog int numlegs = 0 int numlegs = 3 Dog bark();
38 int numlegs = 2 Bird Note also that if we assign the to point to something else, it might not reference the Constant Pool. Constant Pool String <whatever IOHelper returns> Operations like new String(); substring(); and IOHelper.readLine(); cause the allocation of new String objects Bird Dog Bird btemp = new Bird(0); btemp.settype (IOHelper.readLine());
39 What About Non-Instance Data? int numlegs = 0 int numlegs = 3 Dog bark(); The int numlegs was an instance variable of the class, and each instance had its own copy. But the variable int total-- the population counter--was declared static. Thus, it was a class variable. How can we account for this in our diagrams?
40 What About Non-Instance Data? int numlegs = 3 int numlegs = 0 Dog bark(); Class Pool class { public int numlegs; public static int total = 0; private ; public (int numlegs){ this.numlegs = numlegs; strtype = ; total++; public void move ( ) { ( I am an animal and am moving. ); public String { return strtype + with + numlegs + legs. ; // of It just so happens there is something called the Class Pool in Java, which holds information about each class used in your program. You can think of this as the text area where your code is kept. The other parts of memory are the data area where objects are kept.
41 As it turns out, the Class Pool is enormous. It holds not only your classes, but all the classes used by Java--String,, Integer, etc. Every class used to run your program gets loaded here. Java uses the Class Pool to keep track of the working code and methods in each class. Since static variables are of the class and not of the instance, they are kept as part of this storage device. class extends { public (int numlegs){ super(numlegs); strtype = ; public void move( ) { ( Swim, swim, swim, swim! ); // of class Dog extends { public Dog(int numlegs){ super (numlegs); strtype = Dog ; public void move ( ) { ( Run, scratch, walk, run ); public void bark ( ){ ( Arf Arf ); // of Dog (In class ) static int total: 3 Class Pool class Bird extends { public Bird(int numlegs){ super (numlegs); strtype = Bird ; public void move( ) { ( Flap, flap, flap again ); // of Bird class Driver { public static void main (String[ ] argv) { [ ] animalarray = new [3]; int iindex; animalarray[0] = new Bird(2); animalarray[1] = new (0); animalarray[2] = new Dog(3); for (i=0; i < animalarray.length; i++) { (animalarray[i].); animalarray[i].move( ); // of for // of main // of Driver class { public int numlegs; public static int total = 0; private ; public (int numlegs){ this.numlegs = numlegs; strtype = ; total++; public void move ( ) { ( I am an animal and am moving. ); public String { return strtype + with + numlegs + legs. ; // of
42 That s why we can use the class name to invoke class methods, or access class variables. When we access instance variables, however, we must work through an instance of the class. int x =.total; int leg = mydog.getlegcount(); (This assumes we have an accessor; there s not enough room on these slides.) class extends { public (int numlegs){ super(numlegs); strtype = ; public void move( ) { ( Swim, swim, swim, swim! ); // of class Dog extends { public Dog(int numlegs){ super (numlegs); strtype = Dog ; public void move ( ) { ( Run, scratch, walk, run ); public void bark ( ){ ( Arf Arf ); // of Dog (In class ) static int total: 3 Class Pool class Bird extends { public Bird(int numlegs){ super (numlegs); strtype = Bird ; public void move( ) { ( Flap, flap, flap again ); // of Bird class Driver { public static void main (String[ ] argv) { [ ] animalarray = new [3]; int iindex; animalarray[0] = new Bird(2); animalarray[1] = new (0); animalarray[2] = new Dog(3); for (i=0; i < animalarray.length; i++) { (animalarray[i].); animalarray[i].move( ); // of for // of main // of Driver class { public int numlegs; public static int total = 0; private ; public (int numlegs){ this.numlegs = numlegs; strtype = ; total++; public void move ( ) { ( I am an animal and am moving. ); public String { return strtype + with + numlegs + legs. ; // of
43 Style Point: You can also access class members (static stuff) using instance references. Integer itemp = new Integer(3); String strnumber = 42 ; int x = itemp.parseint(strnumber); // OK int y = Integer.parseInt (strnumber); // better There is, however, a convention, of using class names to access class methods/fields. Using an instance of the class also works; however, it gives the impression that it must be done through an instance. So, (1) Use what works. (2) But use what s clear.
44 Back to Polymorphism So, we have these three blocks, representing objects in memory, each different, holding unique references and primitive values. How can these disparate objects be held in an array, which must be homogeneous? int numlegs = 2 Bird int numlegs = 0 int numlegs = 3 Dog bark(); The organizing principle is the shared inherited relationship with. Since, Dog and Bird all extend from, we can make an array to hold different expressions of this class.
45 Back to Polymorphism So, we have these three blocks, representing objects in memory, each different, holding unique references and primitive values. How can these disparate objects be held in an array, which must be homogeneous? int numlegs = 2 Bird int numlegs = 0 int numlegs = 3 Dog bark(); We could also have made an array of types. But we then will have problems invoking methods on members of this array, since lacks key methods--like move().
46 Back to Polymorphism So, we have these three blocks, representing objects in memory, each different, holding unique references and primitive values. How can these disparate objects be held in an array, which must be homogeneous? int numlegs = 2 Bird int numlegs = 0 int numlegs = 3 Dog bark(); So we select as our common type. It s the most specific type, and yet is still held in common by all the members we plan to hold in the array.
47 Back to Polymorphism Bird btemp = new Bird(); otemp = () btemp; atemp = () btemp; Here, the casting is not needed since we are upcasting. It s shown to be explicit. otemp atemp btemp int numlegs = 2 Bird Recall that we can have many reference types pointing to the same or Dog or Bird instance in memory. Thus, since arrays must be of a single type, we just polymorph any references we have into references.
48 Thus, when we have many objects in memory, we polymorph our references to the instances. This gives us an array of types, even though each instance is a different subclass. [ ] final int length = 3 int numlegs = 2 Bird [ 0 ] [ 1 ] [ 2 ] int numlegs = 0 int numlegs = 3 Dog bark(); News Flash: Arrays are objects as well, and extend from. Notice that the int length field of an array is final. We can t resize arrays; we can only make new larger ones and copy the data over. Let s invoke some methods on these objects.
49 Is our picture correct? [ ] final int length = 3 int numlegs = 2 Bird int numlegs = 0 What if we executed this code: otemp; otemp = animalarray[1]; otemp int numlegs = 3 Dog bark(); No. The code works. But our drawing is pointing to the wrong part of our object
50 Is our picture correct? [ ] final int length = 3 int numlegs = 2 Bird int numlegs = 0 What if we executed this code: otemp; otemp = animalarray[1]; otemp int numlegs = 3 Dog bark(); Much better. This fussiness will pay off shortly.
51 Does this work? [ ] final int length = 3 int numlegs = 2 Bird int numlegs = 0 Now, let s add another line of code: otemp; otemp = animalarray[1]; otemp. otemp int numlegs = 3 Dog bark(); NO. The class has no method called move()
52 [ ] final int length = 3 int numlegs = 2 Bird int numlegs = 0 The fix is in: otemp; otemp = animalarray[1]; atemp = () otemp; otemp int numlegs = 3 Dog bark(); atemp Note the explicit down casting was necessary.
53 [ ] final int length = 3 int numlegs = 2 Bird int numlegs = 0 The fix is in: otemp; otemp = animalarray[1]; atemp = () otemp; atemp. otemp int numlegs = 3 Dog bark(); atemp Hmm... Let s look at this closely.
54 otemp; otemp = animalarray[1]; atemp = () otemp; atemp. [ ] final int length = 3 It looks like both and have move() methods. Which one gets called when the atemp.move() line executes? int numlegs = 2 Bird int numlegs = 0 int numlegs = 3 Dog bark(); otemp atemp int numlegs = 0 The reference type we are using is an type. Would that determine whether or has their method called?
55 Dynamic Binding otemp; otemp = animalarray[1]; atemp = () otemp; atemp. Understand this term. Understand what is does. It is a CORE feature of any Oriented language. int numlegs = 0 atemp Here, the principle of dynamic binding will ensure that at run time, the most specific behavior will be invoked. Here, the move() method is more specific than its parent method. So, the s move() method gets called with the atemp.move() line.
56 Sanity Check otemp; otemp otemp = animalarray[1]; atemp = () otemp; (otemp.); What Happens Here? int numlegs = 0 Does casting somehow overpower dynamic binding? What about: ( (()otemp). );
57 Sanity Check otemp; otemp otemp = animalarray[1]; atemp = () otemp; (otemp.); What Happens Here? int numlegs = 0 No matter how you cast things, dynamic binding takes hold. It s like the law of gravity. What about: ( (()otemp). );
58 Sanity Check otemp; otemp otemp = animalarray[1]; atemp = () otemp; (otemp.); What if had its own? int numlegs = 3 No matter how you cast things, dynamic binding takes hold. It s like the law of gravity. Dynamic binding will always resolve, at run time, to the most specific version of the method. ALWAYS.
59 Always? otemp; otemp otemp = animalarray[1]; otemp. // WRONG! Does dynamic binding also work miracles? That is, does it let you find methods in extending classes, if the present class does not have such a method? int numlegs = 3 No such method move() in NO. This would cause a compile time error. Java is strongly typed, meaning that each time you invoke a method, the method MUST be present in the class--even if dynamic binding would later find a more specific version. So: no, dynamic binding does not trump type safety in Java.
60
QUIZ. Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed?
QUIZ Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed? Or Foo(x), depending on how we want the initialization
More informationProgramming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur
Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 43 Dynamic Binding (Polymorphism): Part III Welcome to Module
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 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 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 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 informationBasic Object-Oriented Concepts. 5-Oct-17
Basic Object-Oriented Concepts 5-Oct-17 Concept: An object has behaviors In old style programming, you had: data, which was completely passive functions, which could manipulate any data An object contains
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 informationExample: Count of Points
Example: Count of Points 1 class Point { 2... 3 private static int numofpoints = 0; 4 5 Point() { 6 numofpoints++; 7 } 8 9 Point(int x, int y) { 10 this(); // calling the constructor with no input argument;
More informationtype conversion polymorphism (intro only) Class class
COMP 250 Lecture 33 type conversion polymorphism (intro only) Class class Nov. 24, 2017 1 Primitive Type Conversion double float long int short char byte boolean non-integers integers In COMP 273, you
More informationRelationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor
CSE 143 Object & Class Relationships Inheritance Reading: Ch. 9, 14 Relationships Between Real Things Man walks dog Dog strains at leash Dog wears collar Man wears hat Girl feeds dog Girl watches dog Dog
More informationAgenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java
CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors Agenda
More informationQUIZ. What is wrong with this code that uses default arguments?
QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code
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 informationRelationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor
CSC 143 Object & Class Relationships Inheritance Reading: Ch. 10, 11 Relationships Between Real Things Man walks dog Dog strains at leash Dog wears collar Man wears hat Girl feeds dog Girl watches dog
More informationCS111: PROGRAMMING LANGUAGE II
1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 8(b): Abstract classes & Polymorphism Lecture Contents 2 Abstract base classes Concrete classes Polymorphic processing Dr. Amal Khalifa,
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 informationInheritance and Polymorphism. CS180 Fall 2007
Inheritance and Polymorphism CS180 Fall 2007 Definitions Inheritance object oriented way to form new classes from pre-existing ones Superclass The parent class If class is final, cannot inherit from this
More informationCS121/IS223. Object Reference Variables. Dr Olly Gotel
CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors CS121/IS223
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 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 informationIntroduction to Programming in C Department of Computer Science and Engineering. Lecture No. #34. Function with pointer Argument
Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #34 Function with pointer Argument (Refer Slide Time: 00:05) So, here is the stuff that we have seen about pointers.
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 informationCreate a Java project named week10
Objectives of today s lab: Through this lab, students will examine how casting works in Java and learn about Abstract Class and in Java with examples. Create a Java project named week10 Create a package
More informationRelationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.
CSE 143 Java Object & Class Relationships Inheritance Reading: Ch. 9, 14 Relationships Between Real Things Man walks dog Dog strains at leash Dog wears collar Man wears hat Girl feeds dog Girl watches
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 informationInheritance, polymorphism, interfaces
Inheritance, polymorphism, interfaces "is-a" relationship Similar things (sharing same set of attributes / operations): a group / concept Similar groups (sharing a subset of attributes / operations): a
More informationBM214E Object Oriented Programming Lecture 8
BM214E Object Oriented Programming Lecture 8 Instance vs. Class Declarations Instance vs. Class Declarations Don t be fooled. Just because a variable might be declared as a field within a class that does
More informationCS32 - Week 4. Umut Oztok. Jul 15, Umut Oztok CS32 - Week 4
CS32 - Week 4 Umut Oztok Jul 15, 2016 Inheritance Process of deriving a new class using another class as a base. Base/Parent/Super Class Derived/Child/Sub Class Inheritance class Animal{ Animal(); ~Animal();
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 informationInheritance and Polymorphism
Inheritance and Polymorphism Inheritance (Continued) Polymorphism Polymorphism by inheritance Polymorphism by interfaces Reading for this lecture: L&L 10.1 10.3 1 Interface Hierarchies Inheritance can
More information+ Abstract Data Types
Linked Lists Abstract Data Types An Abstract Data Type (ADT) is: a set of values a set of operations Sounds familiar, right? I gave a similar definition for a data structure. Abstract Data Types Abstract
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 informationCritique this Code. Hint: It will crash badly! (Next slide please ) 2011 Fawzi Emad, Computer Science Department, UMCP
Critique this Code string const & findsmallest(vector const &v) string smallest = v[0]; for (unsigned int i = 0; i < v.size(); i++) if (v[i] < smallest) smallest = v[i]; return smallest; Hint:
More informationInstance Members and Static Members
Instance Members and Static Members You may notice that all the members are declared w/o static. These members belong to some specific object. They are called instance members. This implies that these
More informationCS105 C++ Lecture 7. More on Classes, Inheritance
CS105 C++ Lecture 7 More on Classes, Inheritance " Operator Overloading Global vs Member Functions Difference: member functions already have this as an argument implicitly, global has to take another parameter.
More informationJava for Non Majors. Final Study Guide. April 26, You will have an opportunity to earn 20 extra credit points.
Java for Non Majors Final Study Guide April 26, 2017 The test consists of 1. Multiple choice questions 2. Given code, find the output 3. Code writing questions 4. Code debugging question 5. Short answer
More informationObject Oriented Programming Part II of II. Steve Ryder Session 8352 JSR Systems (JSR)
Object Oriented Programming Part II of II Steve Ryder Session 8352 JSR Systems (JSR) sryder@jsrsys.com New Terms in this Section API Access Modifier Package Constructor 2 Polymorphism Three steps of object
More informationInheritance & Polymorphism
E H U N I V E R S I T Y T O H F R G E D I N B U Murray Cole Classifying Things 1 Hierarchies help us to classify things and understand their similarities and differences Some aspects are common to everything
More informationSurvey #2. Programming Assignment 3. Final Exam. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu.
University of British Columbia CPSC 111, Intro to Computation Alan J. Hu Accessing the Superclass Object Hierarchies is-a, has-a Readings This Week: Ch 9.4-9.5 and into Ch 10.1-10.8 (Ch 11.4-11.5 and into
More informationCS 251 Intermediate Programming Methods and Classes
CS 251 Intermediate Programming Methods and Classes Brooke Chenoweth University of New Mexico Fall 2018 Methods An operation that can be performed on an object Has return type and parameters Method with
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 informationCS 251 Intermediate Programming Methods and More
CS 251 Intermediate Programming Methods and More Brooke Chenoweth University of New Mexico Spring 2018 Methods An operation that can be performed on an object Has return type and parameters Method with
More informationObject Oriented Programming: Based on slides from Skrien Chapter 2
Object Oriented Programming: A Review Based on slides from Skrien Chapter 2 Object-Oriented Programming (OOP) Solution expressed as a set of communicating objects An object encapsulates the behavior and
More informationWhy use inheritance? The most important slide of the lecture. Programming in C++ Reasons for Inheritance (revision) Inheritance in C++
Session 6 - Inheritance in C++ The most important slide of the lecture Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson) Why use inheritance?
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 informationCOMP200 INTERFACES. OOP using Java, from slides by Shayan Javed
1 1 COMP200 INTERFACES OOP using Java, from slides by Shayan Javed Interfaces 2 ANIMAL picture food sleep() roam() makenoise() eat() 3 ANIMAL picture food sleep() roam() makenoise() eat() 4 roam() FELINE
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 informationSupporting Class / C++ Lecture Notes
Goal Supporting Class / C++ Lecture Notes You started with an understanding of how to write Java programs. This course is about explaining the path from Java to executing programs. We proceeded in a mostly
More informationBinghamton University. CS-140 Fall Dynamic Types
Dynamic Types 1 Assignment to a subtype If public Duck extends Bird { Then, you may code:. } Bird bref; Duck quack = new Duck(); bref = quack; A subtype may be assigned where the supertype is expected
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 informationCSSE 220. Interfaces and Polymorphism. Check out Interfaces from SVN
CSSE 220 Interfaces and Polymorphism Check out Interfaces from SVN Interfaces What, When, Why, How? What: Code Structure used to express operations that multiple class have in common No method implementations
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 informationC++ Inheritance and Encapsulation
C++ Inheritance and Encapsulation Private and Protected members Inheritance Type Public Inheritance Private Inheritance Protected Inheritance Special method inheritance 1 Private Members Private members
More informationOverview CSE 142. Naming Revisited Declarations. Defining Parts of Objects
ÿþýûú Overview CSE 142 Anatomy of an object: constructors, methods, and instance variables Quick Review Creating, naming, and using objects Creating (empty) classes and instances of them Today Details
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 informationpublic UndergradStudent(String n, String m, String p) { programme = p; super(n, m);
Tutorial 3: Inheritance Part A Topic: Inheritance 1. Consider the following class definition. class Student { private String name; private String matric_no; a. Write the definition of an empty class named
More informationC++ Important Questions with Answers
1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children
More informationPolymorphism. Arizona State University 1
Polymorphism CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 15 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University
More informationCS1020: DATA STRUCTURES AND ALGORITHMS I
CS1020: DATA STRUCTURES AND ALGORITHMS I 1. Inheritance New McDonald has a farm with some animals. Tutorial 4 Inheritance, Polymorphism (Week 6, starting 15 February 2016) Each animal has a name, and makes
More informationData Structures. Data structures. Data structures. What is a data structure? Simple answer: a collection of data equipped with some operations.
Data Structures 1 Data structures What is a data structure? Simple answer: a collection of data equipped with some operations. Examples Lists Strings... 2 Data structures In this course, we will learn
More informationCITS1001 week 4 Grouping objects
CITS1001 week 4 Grouping objects Arran Stewart March 20, 2018 1 / 31 Overview In this lecture, we look at how can group objects together into collections. Main concepts: The ArrayList collection Processing
More informationAbstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal
Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Define and discuss abstract classes Define and discuss abstract methods Introduce polymorphism Much of the information
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 informationObject Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.
CMSC 131: Chapter 28 Final Review: What you learned this semester The Big Picture Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. Java
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 informationChapter 15: Object Oriented Programming
Chapter 15: Object Oriented Programming Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey How do Software Developers use OOP? Defining classes to create objects UML diagrams to
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 informationWeek 8: Operator overloading
Due to various disruptions, we did not get through all the material in the slides below. CS319: Scientific Computing (with C++) Week 8: Operator overloading 1 The copy constructor 2 Operator Overloading
More informationClarifying Roles. Jonathan Worthington German Perl Workshop 2007
Clarifying Roles Jonathan Worthington German Perl Workshop 2007 The Perl 6 Object Model The Perl 6 object model attempts to improve on the Perl 5 one Nicer, more declarative syntax One way to do things,
More informationWeek 7. Statically-typed OO languages: C++ Closer look at subtyping
C++ & Subtyping Week 7 Statically-typed OO languages: C++ Closer look at subtyping Why talk about C++? C++ is an OO extension of C Efficiency and flexibility from C OO program organization from Simula
More informationClasses, Objects, and OOP in Java. June 16, 2017
Classes, Objects, and OOP in Java June 16, 2017 Which is a Class in the below code? Mario itsame = new Mario( Red Hat? ); A. Mario B. itsame C. new D. Red Hat? Whats the difference? int vs. Integer A.
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 informationJava How to Program, 8/e
Java How to Program, 8/e Polymorphism Enables you to program in the general rather than program in the specific. Polymorphism enables you to write programs that process objects that share the same superclass
More informationJava Primer 1: Types, Classes and Operators
Java Primer 1 3/18/14 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Java Primer 1: Types,
More informationConcepts of Programming Languages
Concepts of Programming Languages Lecture 10 - Object-Oriented Programming Patrick Donnelly Montana State University Spring 2014 Patrick Donnelly (Montana State University) Concepts of Programming Languages
More informationProperties of an identifier (and the object it represents) may be set at
Properties of an identifier (and the object it represents) may be set at Compile-time These are static properties as they do not change during execution. Examples include the type of a variable, the value
More informationBuilding custom components IAT351
Building custom components IAT351 Week 1 Lecture 1 9.05.2012 Lyn Bartram lyn@sfu.ca Today Review assignment issues New submission method Object oriented design How to extend Java and how to scope Final
More informationCS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes
CS/ENGRD 2110 SPRING 2019 Lecture 7: Interfaces and Abstract Classes http://courses.cs.cornell.edu/cs2110 1 Announcements 2 A2 is due Thursday night (14 February) Go back to Lecture 6 & discuss method
More informationQUIZ. How could we disable the automatic creation of copyconstructors
QUIZ How could we disable the automatic creation of copyconstructors pre-c++11? What syntax feature did C++11 introduce to make the disabling clearer and more permanent? Give a code example. QUIZ How
More informationCOMP 250 Fall inheritance Nov. 17, 2017
Inheritance In our daily lives, we classify the many things around us. The world has objects like dogs and cars and food and we are familiar with talking about these objects as classes Dogs are animals
More informationVirtual functions concepts
Virtual functions concepts l Virtual: exists in essence though not in fact l Idea is that a virtual function can be used before it is defined And it might be defined many, many ways! l Relates to OOP concept
More informationOBJECT ORİENTATİON ENCAPSULATİON
OBJECT ORİENTATİON Software development can be seen as a modeling activity. The first step in the software development is the modeling of the problem we are trying to solve and building the conceptual
More informationData Abstraction. Hwansoo Han
Data Abstraction Hwansoo Han Data Abstraction Data abstraction s roots can be found in Simula67 An abstract data type (ADT) is defined In terms of the operations that it supports (i.e., that can be performed
More informationChapter 14 Abstract Classes and Interfaces
Chapter 14 Abstract Classes and Interfaces 1 What is abstract class? Abstract class is just like other class, but it marks with abstract keyword. In abstract class, methods that we want to be overridden
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 informationC10: Garbage Collection and Constructors
CISC 3120 C10: Garbage Collection and Constructors Hui Chen Department of Computer & Information Science CUNY Brooklyn College 3/5/2018 CUNY Brooklyn College 1 Outline Recap OOP in Java: composition &
More informationExample: Count of Points
Example: Count of Points 1 public class Point { 2... 3 private static int numofpoints = 0; 4 5 public Point() { 6 numofpoints++; 7 } 8 9 public Point(int x, int y) { 10 this(); // calling Line 5 11 this.x
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 informationLesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014
Lesson 10A OOP Fundamentals By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Definition Pointers vs containers Object vs primitives Constructors Methods Object class
More informationInheritance CSC 123 Fall 2018 Howard Rosenthal
Inheritance CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Defining what inheritance is and how it works Single Inheritance Is-a Relationship Class Hierarchies Syntax of Java Inheritance The super Reference
More informationThe Dynamic Typing Interlude
CHAPTER 6 The Dynamic Typing Interlude In the prior chapter, we began exploring Python s core object types in depth with a look at Python numbers. We ll resume our object type tour in the next chapter,
More informationUnit 5: More on Classes/Objects Notes
Unit 5: More on Classes/Objects Notes AP CS A The Difference between Primitive and Object/Reference Data Types First, remember the definition of a variable. A variable is a. So, an obvious question is:
More informationQUIZ. How could we disable the automatic creation of copyconstructors
QUIZ How could we disable the automatic creation of copyconstructors pre-c++11? What syntax feature did C++11 introduce to make the disabling clearer and more permanent? Give a code example. Ch. 14: Inheritance
More informationBM214E Object Oriented Programming Lecture 4
BM214E Object Oriented Programming Lecture 4 Computer Numbers Integers (byte, short, int, long) whole numbers exact relatively limited in magnitude (~10 19 ) Floating Point (float, double) fractional often
More informationInheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017
OOP components For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Data Abstraction Information Hiding, ADTs Encapsulation Type Extensibility Operator Overloading
More informationInheritance in Ruby. You are familiar with the idea of inheritance and how to use this in programming.
Inheritance in Ruby You are familiar with the idea of inheritance and how to use this in programming. In this introduction, I'll describe inheritance in Ruby from scratch. Much of this material should
More informationCOMP 110/L Lecture 20. Kyle Dewey
COMP 110/L Lecture 20 Kyle Dewey Outline super in methods abstract Classes and Methods Polymorphism super in Methods Recap You ve seen super in constructors... Recap You ve seen super in constructors...
More informationECE 122. Engineering Problem Solving with Java
ECE 122 Engineering Problem Solving with Java Lecture 17 Inheritance Overview Problem: Can we create bigger classes from smaller ones without having to repeat information? Subclasses: a class inherits
More informationC++ Crash Kurs. Polymorphism. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck
C++ Crash Kurs Polymorphism Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck http://www.itm.uni-luebeck.de/people/pfisterer C++ Polymorphism Major abstractions of C++ Data abstraction
More information