Reviewing Java Implementation Of OO Principles CSC Spring 2019 Howard Rosenthal

Size: px
Start display at page:

Download "Reviewing Java Implementation Of OO Principles CSC Spring 2019 Howard Rosenthal"

Transcription

1 Reviewing Java Implementation Of OO Principles CSC Spring 2019 Howard Rosenthal

2 Course References Materials for this course have utilized materials in the following documents. Additional materials taken from web sites will be referenced when utilized Anderson, Julie and Franceschi Herve, Java Illuminated 5 TH Edition,, Jones and Bartlett, Bravaco, Ralph and Simonson, Shai, Java programming From The Ground Up, McGraw Hill, Deitel, Paul and Deitel, Harvey, Java, How To Program, Early Objects, Tenth Edition, Pearson Publishing, Gaddis, Tony, Starting Out With Objects From Control Structures Through Objects, Pearson Publishing, Horstmann, Cay, Core Java For The Impatient, Addison Wesley- Pearson Education, Schmuller, Joseph, Teach Yourself UML In 24 Hours Second Edition, SAMS Publishing, Urma, Raoul-Gabriel, Fusco, Mario and Mycroft, Alan, Java 8 in Action: Lambdas, Streams, and Functional-Style Programming, Manning Publishing, Wirfs-Brock, Rebecca, Wilkerson, Brian and Wiener, Laura, Designing Object- Oriented Software, Prentice Hall,

3 Lesson Goals Review (from CSC 123) of how basic object-oriented principles are implanted in Java Classes and encapsulation Aggregation Inheritance Abstract Classes Polymorphism Interfaces 3

4 4

5 Classes and Encapsulation 5

6 Encapsulation And UML For An Auto - model : String - int : milesdriven - double : gallonsof Gas Auto + Auto(): + Auto(String : startmodel, int : startmilesdriven, double : startgallonsofgas): + getmodel() : String + getmilesdrivenl() : int + getgallonsofgas() : double + setmodel(string : model) : void + setmilesdrivenl(int : milesdriven) : void + setgallonsofgas(double : gallonsofgas) : void + milespergallon() : double + tostring() : String + equals(object : obj) : boolean Notes: + means public - means private # means protected ~ is for an internal variable Methods without return variables are constructors (some diagrams don t use this convention) constructor(s) still identified by the class name If the title or method is italicized it is an abstract class or method 6

7 Basic class Syntax accessmodifier class ClassName { // class definition goes here } Conventions Use a noun for the class name. Begin the class name with a capital letter 7

8 Basic Terminology Fields Instance variables: the data for each object Class data: static data that all objects share Members Fields and methods Access Modifier Determines access rights for the class and its members Defines where the class and its members can be used 8

9 public vs. private Classes are usually declared to be public We need to be able to access them from other classes or they are useless Instance variables are usually declared to be private. It is good practice to make most instance variables private and only access them through meth0ds of the class We minimize the number of instance values and use methods to obtain derived values Methods that will be called by the client of the class are usually declared to be public. Methods that will be called only by other methods of the class are usually declared to be private. APIs (name and parameters of methods as well as return values) of methods are published (made known) so that clients will know how to instantiate objects and call the methods of the class. 9

10 Instance Variables Each instance of a class has its own set of fields, which are known as instance fields. You can create several instances of a class and store different values in each instance s fields. The methods that operate on an instance of a class are known as instance methods. 10

11 The Syntax Of An Instance Variable Syntax: accessmodifier datatype identifierlist; datatype can be a primitive data type or a class type. identifierlist can contain: One or more variable names of the same data type Multiple variable names separated by commas Initialization values Optionally, instance variables can be declared as final. By convention capitalize any final variables. Conventions Begin the instance variable identifier with a lowercase letter and capitalize internal words as per our normal practices Define instance variables as private so that only the methods of the class will be able to set or change their values. 11

12 Methods In Classes When you write methods for any class follow all the same rules that are normally the case, including those related to overloading. If the method is going to be accessed from another class don t use the word static Special rules relating using static Static methods are convenient for many tasks because they can be called directly from the class, as needed. A static method is created by placing the key word static after the access specifier in the method header. When a class contains a static method, it isn t necessary for an instance of the class to be created in order to execute the method. The only limitation that static methods have is that they cannot refer to non-static members of the class. This means that any method called from a static method must also be static. It also means that if the method uses any of the class s fields, they must be static as well. 12

13 Constructors Constructors are special methods that are called automatically when an object is instantiated using the new keyword Constructors do not have any return value in the header (nor in the body) A constructor is automatically executed each time an object of the class is instantiated. A constructor method has the same name as the class with appendage.java. The only exception to this is when you place multiple classes into the class containing main, in which case the file has the same name as the class containing main. A class can have several constructors. Each constructor must have a different number of parameters or parameters of different types just like an overloaded method. The job of the class constructors is to initialize the instance variables of the new object. If and only if no constructor is specified a default constructor is used. The default constructor for a published class should be published as part of the class API 13

14 Syntax Of The Constructor Syntax: public ClassName( parameter list ) { // constructor body } See AutoClientV1.java, AutoV1.java 14

15 Default Instance Values If the constructor does not assign values to the instance variables, they receive default values depending on the instance variable s data type. (just like arrays) The default constructor doesn t accept arguments. I. The only time that Java provides a default constructor is when you do not write your own constructor for a class. 15

16 A Note About Scope Instance variables have class scope A constructor or method of a class can directly refer to instance variables. We will review the use of the keyword this in a few slides Methods also have class scope A constructor or method of a class can call other methods of a class (without using an object reference). This is just what we have done up to now with methods A method's parameters have local scope A method can directly access its parameters, -but one method's parameters cannot be accessed by other methods. A method can define variables which also have local scope A method can access its local variables, - but one method's local variables cannot be accessed by other methods. 16

17 Accessor Methods Clients cannot directly access private instance variables, so classes provide public accessor methods with this standard form: public returntype getinstancevariable( ) { return instancevariable; } Where (returntype is the same data type as the instance variable.) A simple example looks like this public int getcounter( ) { return counter; } See AutoClientV2.java, AutoV2.java 17

18 Mutator Methods Mutator methods allow the client to change the values of instance variables. They have this general form: public void setinstancevariable( datatype newvalue ) { // if newvalue is valid, // assign newvalue to the instance variable } A simple example: public void setmilesdriven( int newmilesdriven ) { if ( newmilesdriven >= 0 ) milesdriven = newmilesdriven; else { System.out.printf( "Miles driven "cannot be negative.\n" ); System.out.printf( "Value not changed.\n" ); } } See AutoClientV3.java, AutoV3.java and AutoClientV4.java, AutoV4.java (adding some useful methods) 18

19 This Object Reference this How does a method know which object's data to use? The reference this refers to the current instance of a class, the object currently being used. this is an implicit parameter sent to methods. this is an object reference to the object for which the method was called. When a method refers to an instance variable name, this is implied. Thus, variablename is understood to be this.variablename this can be used in any method of the class, including any constructor. Example: public void setinstancevariable(datatype instancevariablename ) { this.instancevariablename = instancevariablename; } In the case above the true instance variable gets the value of the parameter 19

20 Using this (1) public void setinstancevariable(datatype instancevariablename ) { this.instancevariablename = instancevariablename; } Or in a constructor public newobject (datatype1 IVN1, datatype2 IVN2) { this.ivn1 = IVN1; this.ivn2 = IVN2; } See AutoClientV5.java, AutoV5.java 20

21 Using this (2) Some programmers like to use this pattern: public ClassName setinstancevariable( datatype instancevariablename ) { this.instancevariablename = instancevariablename; return this; } Example: public Auto setmodel( String model ) { this.model = model; return this; } See AutoClientV5.java, AutoV5.java 21

22 Calling A Constructor From A Constructor (1) If one constructor calls another constructor, no other statements can precede that call. So look at the following class: public class Room { private int length; private int width; private int height; private double gallonsofpaint; public Room() { length = 9; width =12; height = 8; } public Room(int length,int width, int height) // three-argument constructor { this.length = length; this.width = width; this.height = height; } } You can write it alternatively as shown on the next slide 22

23 Calling A Constructor From A Constructor (2) So look at the following rewritten class: public class Room { private int length; private int width; private int height; private double gallonsofpaint; public Room() { this(9. 12, 8);//does the same thing } public Room(int length,int width, int height) // three-argument constructor { this.length = length; this.width = width; this.height = height; } } 23

24 tostring (1) The tostring() method returns a String representing the data of an object Clients can call tostring() explicitly by coding the method call. Clients can call tostring() implicitly by using an object reference where a String is expected. Example client code: Auto compact = new Auto( ); // instantiate an object // explicit tostring call System.out.printf( %s\n, compact.tostring( ) ); // implicit tostring call System.out.printf( %s\n, compact ); 24

25 tostring (2) Most classes can benefit from having a method named tostring, which is implicitly called under certain circumstances. Typically, the method returns a string that represents the state of an object. Every class has a default tostring() if one isn t provided In general the default it is not all that useful, so we write what is called an overriding method When we look at inheritance we will be understand what is inherited and what is new in tostring() See AutoClientV6.java, AutoV6.java 25

26 Using equals() In Classes The purpose of equals() is to determine if the data in another object is equal to the data in this object. You cannot determine whether two objects contain the same data by comparing them with the == operator. Instead, the class must have a method such as equals for comparing the contents of objects. Like tostring(), equals(object obj) is inherited by every object. However, we almost always want to write an overriding method for your class, based on your definition of equality See AutoClientV6.java, AutoV6.java 26

27 instanceof Is A Special Binary Operator We can use the instanceof operator to determine if an object reference refers to an object of a particular class. instanceof is not really a method, rather it is a special binary operator Syntax: objectreference instanceof ClassName evaluates to true if objectreference is of ClassName type; false otherwise. if (! ( obj instanceof AutoV6 ) ) return false; else o o 0 See AutoClientV6.java, AutoV6.java 27

28 What Does Overriding Mean In any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. We will learn about this in greater detail when we discuss classes and subclasses Some programmer use annotation, (see V6) but it is not required 28

29 Rules For Overriding In Java The argument list should be exactly the same as that of the overridden method. The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass. The access level cannot be more restrictive than the overridden method's access level. For example: If the superclass method is declared public then the overriding method in the sub class cannot be either private or protected. Instance() methods can be overridden only if they are inherited by the subclass. A method declared final cannot be overridden. A method declared static cannot be overridden but can be re-declared. If a method cannot be inherited, then it cannot be overridden. A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final. A subclass in a different package can only override the non-final methods declared public or protected. An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However, the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method. Constructors cannot be overridden. 29

30 static Variables static variables are also known as class variables. A static variable belongs to the class and not to any particular object; a class or static variable is shared by all objects of the class. One copy of a static variable is created per class. static variables are not associated with an object. static constants are often declared as public. When they are they are accessed as classname.variablename i.e. Math.PI To define static data, include the keyword static in its definition: Syntax: accessspecifier static datatype variablename ; Example: private static int countautos = 0; 30

31 Some Uses of static Variables If the class is Employee, keep track of the total number of employees and total payroll with static variables If the class is Car, use a static variable to keep track of the total number of cars sold Keep track of the total number of letters going though a post office with a static variable 31

32 static Methods static methods are also called class methods Often defined to access and change static variables static methods cannot access instance variables: static methods are associated with the class, not with any object. static methods do not have access to the implicit parameter this remember this is a reference to the object. static methods cannot access non-static methods To be accessed outside the class the method must be public You access a class method as follows classname.method(parameter list) classname is not needed within the class, only for external access Example: Math.sqrt(value) See AutoClientV7.java, AutoV7.java 32

33 Access Restrictions For static And Non-static Methods Exception: A static method may be called whether or not an object of the class exists, but a static method cannot invoke an instance method except via an object. For example, main is static, but it can invoke nonstatic method of a class via the object reference. 33

34 Aggregation 34

35 A UML Envisioning Of A Course 35

36 Discussion On UML For the Instructor class The Instructor class Three instance variables - the instructor s last name, first name and office number A constructor which accepts arguments for the instructor s last name, first name and office number A copy constructor A set method, which can be used to set all of the class s fields A tostring method See Instructor.java code 36

37 Discussion On UML For the Textbook class The Textbook class Three instance variables - the title, author and publisher A constructor which accepts arguments for the title, author and publisher A copy constructor A set method, which can be used to set all of the class s fields A tostring method See TextBook.java code 37

38 Aggregation Example The Course class The Course class has an Instructor object and a TextBook object as fields, as well as a course name Making an instance of one class a field in another class is called object aggregation. The word aggregate means a whole which is made of constituent parts. In this example, the Course class is an aggregate class because it is made of constituent objects. When an instance of one class is a member of another class, it is said that there is a has a relationship between the classes. For example, the relationships that exist among the Course, Instructor, and TextBook classes can be described as follows: The course has an instructor. The course has a textbook The has a relationship is sometimes called a whole-part relationship because one object is part of a greater whole. 38

39 Discussion On UML For the Course class The Course class Three instance variables - the coursename, Instructor and TextBook A constructor which accepts arguments for the the coursename, Instructor and TextBook A getname method to get the name of the course A getinstructor method to get a reference to a instructor object A gettextbook method to get a reference of the textbooks ListArray A tostring method See Course.java code Then see CourseDemo.java 39

40 Inheritance 40

41 Specifying Inheritance In Java The syntax for defining a subclass is to use the extends keyword in the class header, as in accessmodifier class SubclassName extends SuperclassName { // class definition new variables, constructors and other methods (new or overriding) } The superclass name specified after the extends keyword is called the direct superclass. As mentioned, a subclass can have many superclasses, but only one direct superclass. 41

42 A Simple Example With Inheritance Let s look at the following files: TestVideoStore.java, Video.java, Movie.java The class Movie is a subclass of Video. An object of type Movie has these members: member member member title length avail director rating tostring() inherited from Video inherited from Video inherited from Video defined in Movie defined in Movie inherited from Video gettitle() getlength() getavailabl e() getdirector () getrating() inherited from Video inherited from Video inherited from Video defined in Movie defined in Movie settitle() setlength() setavailable () inherited from Video inherited from Video inherited from Video 42

43 Using A Super Constructor (1) Look at he constructor for class Movie. The class definition for Video has a constructor that initializes the instance variables of Video objects. The class Movie has a constructor that initializes the instance variables of Movie objects. The statement super(ttl, lngth) invokes a constructor of the parent to initialize some variables of the child. There are two constructors in the parent. The one that is invoked is the one that matches the argument list in super(ttl, lngth). The next two statements initialize variables that only Movie has. Important Note: super() must be the first statement in the subclass's constructor. super() will be inserted into any constructor of the subclass as the first statement if you do not do not explicitly use a super constructor. If you have more than one constructor in the subclass you can use the super() with or without parameter as appropriate. 43

44 Using A Super Constructor (2) An example. If the code looks like this: public Movie( String ttl, int lngth, String dir, String rtng ) { settitle( ttl ); // initialize inherited variables setlength( lngth ); setavailable( true ); director = dir; // initialize Movie variables rating = rtng; } Then the following insert takes place: public Movie( String ttl, int lngth, String dir, String rtng ) { super(); // inserted by compiler: parent's no-argument constructor settitle( ttl ); // initialize inherited variables setlength( lngth ); setavailable( true ); director = dir; // initialize Movie variables rating = rtng; } Note: In our program the class definition for Video (the superclass) lacks a noargument constructor. The proposed constructor (above) calls for such a constructor so it would cause a syntax error. 44

45 A Few Notes About The Default Constructor The programmer can explicitly write a no-argument constructor for a class. If the programmer does not write any constructors for a class, then a no-argument constructor (called the default constructor) is automatically supplied. If the programmer writes even one constructor for a class then the default constructor is not automatically supplied. So: if you write a constructor for a class, then you must also write a no-argument constructor if one is expected. Look at Test2VideoStore.java 45

46 Inheritance Rules for Constructors 46

47 Overriding A Parent Method A child's method overrides a parent's method when it has the same signature as a parent method. Remember that the signature of a method is the name of the method and its parameter list. When overriding a method with the same signature you can change the return type under certain conditions. Overriding method can have different return type but this new type must be A non-primitive and A subclass of what base class s overridden method is returning (i.e. co-variant Return Type). Example if a reference to a Video is returned in the superclass a reference to a Movie can be returned in the subclass method that is overriding Now the parent has its method, and the child has its own method with the same signature. Now look at Test3VideoStore.java and Movie3.java to see the overriding of tostring() in Movie You can also incorporate super in the process to print out the common parts the same way. 47

48 Inheritance Rules For Overwritten Methods 48

49 private Variables and Methods In A Superclass Superclass members declared as private are not inherited, although they are part of the subclass. Thus, a title, length and avail instance variable is allocated to all Movie objects, but methods of the Movie class cannot directly access title, length or avail directly. To set or get the value of title, length or avail, the Movie methods must call the inherited getxxx methods, which are public methods. This simplifies maintenance because the Video class enforces the data validation rules for title, length or avail. 49

50 protected Variables and Methods In A Superclass protected members are inherited by subclasses (like public members), while still being hidden from client classes (like private members). This means that the variables and methods that are protect can be directly accessed Also, any class in the same package as the superclass can directly access a protected field, even if that class is not a subclass. Disadvantage: Because more than one class can directly access a protected field, protected access compromises encapsulation and complicates maintenance. For that reason, we prefer to use private, rather than protected, for our instance variables. 50

51 A Few More Notes On protected Members Declaring fields as private preserves encapsulation. Subclass methods call superclass methods to set the values of the fields, and the superclass methods enforce the validation rules for the data. However, calling methods incurs processing overhead. Declaring fields as protected allows them to be accessed directly by subclass methods. Classes outside the hierarchy and package must use accessors and mutators for protected fields. Advantage: protected fields can be accessed directly by subclasses, so there is no method-invocation overhead. Disadvantage: Maintenance is complicated because the subclass also needs to enforce validation rules. Recommendation: Define protected fields only when high performance is necessary. Avoid directly setting the values of protected fields in the subclass. 51

52 Inheritance Rules For Classes and Subclasses 52

53 The Object Class All classes have a parent class (have a super class) except one. The class at the top of the Java class hierarchy is called Object. If a class definition does not extend a parent class then it automatically has Object as a parent class. If a class definition does extend a parent class, then if the parent class does not extend a parent it automatically has Object as a parent class. And so on. Ultimately all classes have Object as an ancestor. This means that all classes in Java share some common characteristics. Those characteristics are defined in Object. For example, all classes have a tostring() method because the class Object defines that method so all classes get it by inheritance. Of course, usually when you write a class you override the tostring() method. Constructors for our classes have not mentioned Object. According to the rule, the compiler automatically does this: public Video( String ttl, int lngth ) { super(); // use the super class's constuctor title = ttl; length = lngth; avail = true; } And Video automatically has what is in red done: class Video extends Object 53

54 The Java Hierarchy for Video 54

55 Abstract Classes 55

56 Abstract Classes An abstract class in Java is a class that is never instantiated. Its purpose is to be a parent to several related classes. The children classes inherit from the abstract parent class. It is defined like this: abstract class ClassName {..... // definitions of methods and variables } Access modifiers such as public can be placed before abstract. Even though it can not be instantiated, an abstract class defines methods and variables that children classes inherit, as we will shortly describe 56

57 The Structure Of An Abstract Class A simple framework for abstraction. Note that the method has no body abstract class Card { protected String recipient; // name of who gets the card public abstract void greeting(); // abstract greeting() method - There is no body } Since no constructor is defined in Card the default noargument constructor is automatically supplied by the compiler. However, this constructor cannot be used directly because no Card object can be constructed. Why? Because abstract classes can t be used to create objects. 57

58 Extending An Abstract Class (1) Below is an example that extends Card class Holiday extends Card { public Holiday( String r ) { recipient = r; // recipient in Card is protected, so this works } public void greeting() { System.out.printf("Dear %s\n", recipient); System.out.printf("Season's Greetings!\n"); } } Look at CardTesterV2.java to see how we can instantiate a Holiday Card with different greetings See Holiday.java, Valentine.java, Birthday.java and CardTesterV3.java to demonstrate how you can create multiple classes from a single abstraction, and then create objects from any of those classes 58

59 Extending An Abstract Class (2) The class Holiday is not an abstract class. Objects can be instantiated from it. Its constructor implicitly calls the no-argument constructor in its parent, Card, which calls the constructor in Object. So even though it has an abstract parent, a Holiday object is just as much an object as any other. Notes: Holiday inherits the abstract method greeting() from its parent. Holiday must define a greeting() method that includes a method body (statements between braces). The definition of greeting() must match the signature given in the parent. If Holiday did not define greeting(), then Holiday must be declared to be an abstract class. This would make it an abstract child of an abstract parent. 59

60 Abstract Methods An abstract method has no body. It declares an access modifier, return type, and method signature followed by a semicolon. It has no statements. A non-abstract child class inherits the abstract method and must define a non-abstract method that matches the abstract method. Abstract classes can (but don't have to) contain abstract methods. Also, an abstract class can contain non-abstract methods, which will be inherited by the children. An abstract child of an abstract parent does not have to define non-abstract methods for the abstract signatures it inherits. This means that there may be several steps between an abstract base class to a child class that is completely non-abstract. (You don t need to define each method the first step down. 60

61 Defining An Abstract Method To declare a method as abstract, include the abstract keyword in the method header, and end the header with a semicolon: accessmodifier abstract returntype methodname( argument list ); Note: The semicolon at the end of the header indicates that the method has no code. We do not use opening and closing curly braces.{ 61

62 Method Signature Quick Reminder: A signature looks like this: somemethod( int, double, String ) The return type is not part of the signature. The names of the parameters do not matter, just their types. The name of a method is not enough to uniquely identify it. There may be several versions of a method, each with different parameters. The types in the parameter are needed to specify which method you want. 62

63 Restriction When Defining Abstract Methods An abstract method definition consists of: optional access modifier (public, private, and others), the reserved word abstract, the type of the return value, a method signature, a semi-colon. no braces for a body abstract methods can be declared only within an abstract class. An abstract method must consist of a method header followed by a semicolon. abstract methods cannot be called. abstract methods cannot be declared as private or static. A constructor cannot be declared abstract. 63

64 Polymorphism 64

65 What Is Polymorphism? An important concept in inheritance is that an object of a subclass is also an object of any of its superclasses. That concept is the basis for an important OOP feature called polymorphism. Polymorphism means "having many forms." In Java, it means that one variable might be used with several objects of related classes at different times in a program. Polymorphism simplifies the processing of various objects in the same class hierarchy because we can use the same method call for any object in the hierarchy using a superclass object reference. 65

66 An Intuitive Introduction To Polymorphism University Community Students Faculty Administrators Fine Arts Faculty Physics Faculty Computer Science Faculty 66

67 Discussion Of The University Hierarchy Could you add a Faculty member to the list of the University Community without problem? Could it work the opposite way? This is what polymorphism is about, the ability to organize and call objects based on their parents. You couldn t put a Fine Arts Faculty member in the Computer Science Faculty List. So when you take an object off a higher level list you may need to determine what kind of lower level object it actually is. 67

68 Using Polymorphism To use polymorphism, these conditions must be true: The classes are in the same hierarchy. All subclasses override the same method(s). A subclass object reference is assigned to a superclass object reference. The superclass object reference is used to call the overridden method. 68

69 Extending Classes and Polymorphism class YouthBirthday extends Birthday { public YouthBirthday ( String r, int years ) { super ( r, years ) } // additional method---does not override parent's method Different Signature public void greeting( String sender ) { super.greeting(); System.out.printf("How you have grown!!\n\n"); System.out.printf("Love, %s\n, sender); } } See CardTestV5.java, YouthBirthday.java, AdultBirthday.java 69

70 An Example Of Polymorphism In the example below we create a variable card of type Card We can now use this variable for any subclass of that superclass public class CardTesterV4 { public static void main ( String[] args ) { Card card = new Holiday( "Amy" ); card.greeting(); //Invoke a Holiday greeting() card = new Valentine( "Bob", 3 ); card.greeting(); //Invoke a Valentine greeting() card = new Birthday( "Cindy", 17 ); card.greeting(); //Invoke a Birthday greeting() } } 70

71 Snap Check 1 Here are some variable declarations: Card c; Birthday b; Valentine v; Holiday h; Which of the following are correct given our prior class definitions? c = new Valentine("Debby", 8); b = new Valentine("Elroy", 3); v = new Valentine("Fiona", 3); h = new Birthday ("Greg", 35); 71

72 Snap Check 1 Answers Card c; Birthday b; Valentine v; Holiday h; c = new Valentine("Debby", 8); //OK b = new Valentine("Elroy", 3); //WRONG v = new Valentine("Fiona", 3); //OK h = new Birthday ("Greg", 35); //WRONG 72

73 Snap Check 2 Given the definitions below and the Hierarchy to the left: Rodent rod; Rat rat; Mouse mou; Fill in the chart code section OK or Not? code section OK or Not? rod = new Rat(); mou = new Rat(); rat = new Rodent(); rat = new FieldMouse(); rod = new FieldMouse(); mou = new Rodent(); rat = new LabRat(); rat = new Mouse(); 73

74 Snap Check 2 Answers Giventhe definitions below and the Hierarchy to the left: Rodent rod; Rat rat; Mouse mou; Fill in the chart code section OK or Not? code section OK or Not? rod = new Rat(); mou = new Rat(); rat = new Rodent(); rat = new FieldMouse(); OK Wrong Wrong Wrong rod = new FieldMouse(); mou = new Rodent(); rat = new LabRat(); OK Wrong OK rat = new Mouse(); Wrong 74

75 Referencing Subclass Objects with Subclass vs Superclass Reference A Deeper Explanation (1) There are two approaches to refer to a subclass object. Both have some advantages/disadvantages over the other. The declaration affect is seen on methods that are visible at compile-time. First approach (Referencing using Superclass reference): A reference variable of a superclass can be used to refer to any subclass object derived from that superclass. If the methods are present in SuperClass, but overridden by SubClass, it will be the overridden method that will be executed. Second approach (Referencing using subclass reference) : A subclass reference can be used to refer its object. See Programs Bicycle.java, MountainBike.java, TestBikes.java 75

76 Referencing Subclass Objects with Subclass vs Superclass Reference A Deeper Explanation (2) The object of MountainBike class is created which is referred by using subclass reference mb1. MountainBike mb1 = new MountainBike(3, 100, 25); Using this reference we will have access both parts(methods and variables) of the object defined by the superclass or subclass. See below image for clear understanding. 76

77 Referencing Subclass Objects with Subclass vs Superclass Reference A Deeper Explanation (3) Now we again create object of MountainBike class but this time it is referred by using superclass Bicycle reference mb2. Using this reference we will have access only to those parts(methods and variables) of the object defined by the superclass. Bicycle mb2 = new MountainBike(4, 200, 20); 77

78 Referencing Subclass Objects with Subclass vs Superclass Reference A Deeper Explanation (4) If there are methods present in super class, but overridden by subclass, and if object of subclass is created, then whatever reference we use(either subclass or superclass), it will always be the overridden method in subclass that will be executed. In our example, we have seen that by using reference mb2 of type Bicycle, we are unable to call subclass specific methods or access subclass fields. In general, a superclass reference cannot reference subclass specific methods This problem can be solved using type casting in java. For example, we can declare another reference say mb3 of type MountainBike and assign it to mb2 using typecasting. // declaring MountainBike reference MountainBike mb3; // assigning mb3 to mb2 using typecasting. mb3 = (MountainBike)mb2; 78

79 Referencing Subclass Objects with Subclass vs Superclass Reference A Deeper Explanation (5) Summary Of Polymorphic Reference Usage subclass v. superclass Advantage We can use superclass reference to hold any subclass object derived from it. Disadvantage By using superclass reference, we will have access only to those parts(methods and variables) of the object defined by the superclass. For example, we can not access seatheight variable or call setheight(int newvalue) method using Bicycle reference in above first example. This is because they are defined in subclass not in the superclass. 79

80 The instanceof Operator (1) We ve already been using this operator in our equals() methods. Look at the example below: Object obj; YouthBirthday ybd = new YouthBirthday( "Ian", 4 ); String str = "Yertle"; obj = ybd; if ( obj instanceof YouthBirthday ) ((YouthBirthday)obj).greeting(); else if ( obj instanceof String ) System.out.printf( %s\n, (String)obj ); 80

81 The instanceof Operator (2) The format of instance of is: variable instanceof Class A typecast is used to tell the compiler what is really in a variable that itself is not specific enough. You have to tell the truth. In a complicated program, a reference variable might end up with any of several different objects, depending on the input data or other unpredictable conditions. The instanceof operator evaluates to true or false depending on whether the variable refers to an object of its operand. Also, instanceof will return true if variable is a descendant of Class. It can be a child, a grandchild, a greatgrandchild, or... of the class. 81

82 Interfaces 82

83 Defining An interface (1) An interface has the following form: interface InterfaceName { constant definitions method headers (without implementations). } As previously described, a A method header is an access modifier, a return type, the method name, a parameter list followed by a semicolon. You can put an interface in its own source file or include it with other classes in a source file. In either case, the source file ends with the extension.java The methods in an interface are public by default, so you can omit public from the method headers. The methods cannot be private and cannot be protected prior to Java 9 An interface looks somewhat like a class definition. But no objects can be constructed from it. However, you can define a class that implements an interface, and once you have done that you can construct objects of that class. 83

84 Defining An interface (2) A class implements an interface by doing this: class SomeClass extends SomeParent implements InterfaceName1, InterfaceName2,. { } Rules A class extends just one parent, but may implement multiple interfaces. A method in an interface cannot be made private. A method in an interface is public by default. The constants in an interface are public static final by default. Recall that final means that the value cannot change as the program is running. 84

85 Defining An interface Look at these two examples: Example 1: interface MyInterface { public static final int ACONSTANT = 32; // a constant public static final double PI = ; // a constant public void methoda( int x ); // a method header public double methodb(); // a method header } Example 2: interface MyInterface { int ACONSTANT = 32; // a constant (public static final, by default) double PI = ; // a constant (public static final, by default) void methoda( int x ); // a method header (public, by default) double methodb(); // a method header (public, by default) } The second interface (above) is the preferred way to define an interface. The defaults are assumed and not explicitly coded. 85

86 Snap Check What is wrong with the following interface? interface SomeInterface { public final int x = 32; public double y; public double addup( ); } 86

87 Rules For Implementing An interface A class that implements an interface must implement each method in the interface. Methods from the interface must be declared public in the class. This is changed in Java v9, but most computers at CSUDH are still running Java 8, so we will stick with public interfaces Constants from the interface can be used as if they had been defined in the class. Constants should not be redefined in the class. Any number of classes can implement the same interface. The implementations of the methods listed in the interface can be different in each class. 87

88 A Recent Change In interface Before Java 8, interfaces could have only abstract methods. The implementation of these methods has to be provided in a separate class. So, if a new method is to be added in an interface, then its implementation code has to be provided in the class implementing the same interface. To overcome this issue, Java 8 has introduced the concept of default methods which allow the interfaces to have methods with implementation without affecting the classes that implement the interface. The default methods were introduced to provide backward compatibility so that existing interfaces can use the lambda expressions without implementing the methods in the implementation class. default is used as a modifier of the method A default method can still be overridden Default methods are also known as defender methods or virtual extension methods. 88

89 Static Methods In Interfaces Another feature that was added in JDK 8 is that we can now define static methods in interfaces which can be called independently without an object. Note: these methods are not inherited. 89

90 Programming Exercise 1 (Classes) CellPhone and CellPhoneTester Wireless Solutions, Inc., is a business that sells cell phones and wireless service. You are a programmer in the company s information technology (IT) department, and your team is designing a program to manage all of the cell phones that are in inventory. You have been asked to design a class that represents a cell phone. The data that should be kept as fields in the class are as follows: The name of the phone s manufacturer will be assigned to the manufact field. The phone s model number will be assigned to the model field. The phone s retail price will be assigned to the retailprice field. The class will also have the following methods: A constructor that accepts arguments for the manufacturer, model number and retail price. A setmanufact method that accepts an argument for the manufacturer. This method will allow us to change the value of the manufact field after the object has been created, if necessary. A setmodel method that accepts an argument for the model. This method will allow us to change the value of the model field after the object has been created, if necessary. A setretailprice method that accepts an argument for the retail price. This method will allow us to change the value of the retailprice field after the object has been created, if necessary. A getmanufact method that returns the phone s manufacturer. A getmodel method that returns the phone s model number. A getretailprice method that returns the phone s retail price. A tostring method that prints out the phone s manufacture, model and price. Write a program that creates a CellPhone object and tests all the methods 90

91 Programming Exercise 2 (1) - Aggregation Modifying the CourseDemo and Course and other classes Download the 4 classes For this example the Instructor and TextBook classes remain unchanged. Relabel CourseDemo and Course as CourseDemoV2 and CourseV2 in the file and class name In CourseV2 Change the constructor by eliminating the TextBook variable. For an instance variable create an ArrayList of TextBook objects remember to import ArrayList Create an void addtextbook(textbook) method with appropriate code to add a TextBook to the ArrayList Modify tostring so that it prints out each TextBook in the ArrayList 91

92 Programming Exercise 2 (2 ) - Aggregation Modifying the CourseDemo and Course and classes In CourseDemoV2 Create the Course as in current example (hard coded, but eliminate the TextBook from the constructor call) Read in the file name containing a list of text books for the course (you can download textbooks.txt). The format of the file has the format for each textbook on three lines containing: Title Author Publisher Create a Scanner to read in the file Read in three lines Create a TextBook Call addtextbook to add a new text book for the course Note: A better model might have the Instructor adding the TextBook(s) for the course 92

93 Programming Exercise 3 Inheritance Extending A class (1) Extending the Game class Download the Game class from Lesson 12 Classwork and read its structure Create a subclass PCBasedGame Add three new instance values minimum megabytes of RAM required, minimum number of disk megabytes required, (both as type int), and required gigahertz speed of processor (as a double) Create accessors and mutators for each new instance variable Create an overriding tostring() method and equals() method equals method is true if each pair of instance variables are equal Write a PCBasedClient class with the main program that does the following Reads in the description, required RAM MBs, disk MBs and Gigahertz speed for a PCBasedGame object pcbg1. Create a pcbg1 object Use tostring to print out pcbg1 Reads in the description, required RAM MBs, disk MBs and Gigahertz speed for a PCBasedGame object pcbg2. Create a pcbg2 object Use tostring to print out pcbg2 Use equals to check equality between the two games Use accessors and mutators to set all pcbg2 instance variable values to pcbg1 values Now use equals again to check between the two games 93

94 Programming Exercise 3 Inheritance Extending A class (2) Sample IO Please enter the game description for game one: Monopoly Please enter the required RAM MBs and Disk Size MBs for game one as type int: Please enter the required CPU speed in Gigahertz for game one as a double: 32.7 Game Description: Monopoly Minimum configuration: RAM: 24 MB; hard disk: 120 MB; CPU GHZ Please enter the game description for game two: Scrabble Please enter the required RAM MBs and Disk Size MBs for game two as type int: Please enter the required CPU speed in Gigahertz for game two as a double: 45.2 Game Description: Monopoly Minimum configuration: RAM: 24 MB; hard disk: 120 MB; CPU GHZ pcbg1 and pcbg2 are not equal pcbg1 and pcbg2 are now equal 94

95 Programming Exercise 4 An abstract class Extending the abstract class Shape Create an abstract superclass Shape. Shape has two abstract methods, perimeter and area, and a final constant field named PI. Create two non-abstract subclasses, one encapsulating a Circle, the other a Rectangle. Rectangle has two additional attributes, length and width of type double. Circle has one additional attribute, its radius of type double. Write a TestShape class with a main method that tests out the above. Read in the length and width of a rectangle and print out the perimeter and area. Read in the radius of a rectangle and print out the perimeter (circumference) and area. 95

96 Programming Exercise 5 Polymorphism Implement the following classes Abstract Vehicle class Write an abstract superclass encapsulating a Vehicle. A Vehicle has two attributes = owner (String) and wheels (an int) Write accessor and mutator methods for both attributes. Write methods for a tostring that includes the owner and the number of wheels. Write an equals() method that is true if both attributes are equal when comparing two vehicles. Bicycle class Write a class encapsulating a Bicycle that extends Vehicle that only has a constructor and no overriding methods. The Bicycle only has an owner and wheels. MotorizedVehicle class Write a class encapsulating a MotorizedVehicle that extends Vehicle. There is one extra attribute for volume displacement. There is one extra accessor and one extra mutator. There is one extra method computing horsepower which is the volume displacement times the number of wheels. You should also override the to String() and equals() method, taking into account the third attribute VehicleClient class which includes the main method. Read in 4 different vehicles, a mix of 2 bikes and 2 motorized vehicles into an ArrayList of type Vehicle, each with different values for the attributes. reads in the attributes for two Motorized objects. Uses the tostring() method to print out the 4 vehicles as appropriate Use the equals() to compare the two motorized vehicles and two bicycles, print out results It set the second motorized vehicle s attributes equal to the first s and retest with the equals() method. 96

97 Programming Exercise 6 Adding More interfaces Adding more interfaces Copy Goods.java, Food.java, Book.java, Toy.java and Taxable.java Create a new interface called Returnable with a boolean method canreturn: boolean canreturn(double threshold); Implement Returnable in Book and in Toy to return true if the value of the Book is greater than a threshold Modify a version of TestStore.java to check this feature for each of the two classes obtaining both true and false features. Read in a threshold for each class. 97

Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal

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

A Formal Presentation On Writing Classes With Rules and Examples CSC 123 Fall 2018 Howard Rosenthal

A Formal Presentation On Writing Classes With Rules and Examples CSC 123 Fall 2018 Howard Rosenthal A Formal Presentation On Writing Classes With Rules and Examples CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Defining a Class Defining Instance Variables Writing Methods The Object Reference this The

More information

Inheritance CSC 123 Fall 2018 Howard Rosenthal

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

Interfaces CSC 123 Fall 2018 Howard Rosenthal

Interfaces CSC 123 Fall 2018 Howard Rosenthal Interfaces CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Defining an Interface How a class implements an interface Using an interface as a data type Default interfaces Implementing multiple interfaces

More information

3. Can an abstract class include both abstract methods and non-abstract methods? D

3. Can an abstract class include both abstract methods and non-abstract methods? D Assignment 13 Abstract Classes and Polymorphism CSC 123 Fall 2018 Answer Sheet Short Answers. Multiple Choice 1. What is an abstract class? C A. An abstract class is one without any child classes. B. An

More information

Introduction To Software Development CSC Spring 2019 Howard Rosenthal

Introduction To Software Development CSC Spring 2019 Howard Rosenthal Introduction To Software Development CSC 295-01 Spring 2019 Howard Rosenthal Course References Materials for this course have utilized materials in the following documents. Additional materials taken from

More information

CS-202 Introduction to Object Oriented Programming

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

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Contents. 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 information

What is Inheritance?

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

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U C A N A D I A N I N T E R N A T I O N A L S C H O O L O F H O N G K O N G INHERITANCE & POLYMORPHISM P2 LESSON 12 P2 LESSON 12.1 INTRODUCTION inheritance: OOP allows a programmer to define new classes

More information

Computer Science 210: Data Structures

Computer Science 210: Data Structures Computer Science 210: Data Structures Summary Today writing a Java program guidelines on clear code object-oriented design inheritance polymorphism this exceptions interfaces READING: GT chapter 2 Object-Oriented

More information

ITI Introduction to Computing II

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

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

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

Computer Science II (20073) Week 1: Review and Inheritance

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

Java Object Oriented Design. CSC207 Fall 2014

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

CS260 Intro to Java & Android 03.Java Language Basics

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

ITI Introduction to Computing II

ITI 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 21, 2013 Abstract

More information

Inheritance -- Introduction

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

Inheritance. 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 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 information

An Introduction To Writing Your Own Classes CSC 123 Fall 2018 Howard Rosenthal

An Introduction To Writing Your Own Classes CSC 123 Fall 2018 Howard Rosenthal An Introduction To Writing Your Own Classes CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Understand Object Oriented Programming The Syntax of Class Definitions Constructors this Object Oriented "Hello

More information

More on Inheritance. Interfaces & Abstract Classes

More on Inheritance. Interfaces & Abstract Classes More on Inheritance Interfaces & Abstract Classes Java interfaces A Java interface is used to specify minimal functionality that a client requires of a server. A Java interface contains: method specifications

More information

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CS5000: 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 information

Inheritance (continued) Inheritance

Inheritance (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 information

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini 22. Inheritance Java Summer 2008 Instructor: Dr. Masoud Yaghini Outline Superclasses and Subclasses Using the super Keyword Overriding Methods The Object Class References Inheritance Object-oriented programming

More information

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini 24. Inheritance Java Fall 2009 Instructor: Dr. Masoud Yaghini Outline Superclasses and Subclasses Using the super Keyword Overriding Methods The Object Class References Superclasses and Subclasses Inheritance

More information

CS 251 Intermediate Programming Inheritance

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

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

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

Inheritance, Polymorphism, and Interfaces

Inheritance, 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 information

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

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

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

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

Java: introduction to object-oriented features

Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer

More information

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods. Inheritance Inheritance is the act of deriving a new class from an existing one. Inheritance allows us to extend the functionality of the object. The new class automatically contains some or all methods

More information

Chapter 9: A Second Look at Classes and Objects

Chapter 9: A Second Look at Classes and Objects Chapter 9: A Second Look at Classes and Objects Starting Out with Java: From Control Structures through Objects Fourth Edition by Tony Gaddis Addison Wesley is an imprint of 2010 Pearson Addison-Wesley.

More information

INHERITANCE. Spring 2019

INHERITANCE. Spring 2019 INHERITANCE Spring 2019 INHERITANCE BASICS Inheritance is a technique that allows one class to be derived from another A derived class inherits all of the data and methods from the original class Suppose

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

C++ Important Questions with Answers

C++ 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 information

Inheritance and Polymorphism

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

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

OBJECT ORİENTATİON ENCAPSULATİON

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

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

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

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

11/19/2014. Inheritance. Chapter 7: Inheritance. Inheritance. Inheritance. Java Software Solutions for AP* Computer Science A 2nd Edition

11/19/2014. Inheritance. Chapter 7: Inheritance. Inheritance. Inheritance. Java Software Solutions for AP* Computer Science A 2nd Edition Chapter 7: Inheritance Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition by John Lewis, William Loftus, and Cara Cocking Inheritance Inheritance allows a software developer

More information

Inheritance. The Java Platform Class Hierarchy

Inheritance. The Java Platform Class Hierarchy Inheritance In the preceding lessons, you have seen inheritance mentioned several times. In the Java language, classes can be derived from other classes, thereby inheriting fields and methods from those

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

Super-Classes and sub-classes

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

Inheritance and Polymorphism

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

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism. Outline Inheritance Class Extension Overriding Methods Inheritance and Constructors Polymorphism Abstract Classes Interfaces 1 OOP Principles Encapsulation Methods and data are combined in classes Not

More information

Introduction to Inheritance

Introduction to Inheritance Introduction to Inheritance James Brucker These slides cover only the basics of inheritance. What is Inheritance? One class incorporates all the attributes and behavior from another class -- it inherits

More information

Lecture Notes Chapter #9_b Inheritance & Polymorphism

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

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

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

8. Polymorphism and Inheritance

8. 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 information

CH. 2 OBJECT-ORIENTED PROGRAMMING

CH. 2 OBJECT-ORIENTED PROGRAMMING CH. 2 OBJECT-ORIENTED PROGRAMMING ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016) OBJECT-ORIENTED

More information

by Pearson Education, Inc. All Rights Reserved. 2

by Pearson Education, Inc. All Rights Reserved. 2 Suppose you want to drive a car and make it go faster by pressing down on its accelerator pedal. Before you can drive a car, someone has to design it and build it. A car typically begins as engineering

More information

BBM 102 Introduction to Programming II Spring Inheritance

BBM 102 Introduction to Programming II Spring Inheritance BBM 102 Introduction to Programming II Spring 2018 Inheritance 1 Today Inheritance Notion of subclasses and superclasses protected members UML Class Diagrams for inheritance 2 Inheritance A form of software

More information

Chapter 11: Inheritance

Chapter 11: Inheritance Chapter 11: Inheritance Starting Out with Java: From Control Structures through Objects Fourth Edition by Tony Gaddis Addison Wesley is an imprint of 2010 Pearson Addison-Wesley. All rights reserved. Reading

More information

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

IST311. Advanced Issues in OOP: Inheritance and Polymorphism IST311 Advanced Issues in OOP: Inheritance and Polymorphism IST311/602 Cleveland State University Prof. Victor Matos Adapted from: Introduction to Java Programming: Comprehensive Version, Eighth Edition

More information

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

Distributed Systems Recitation 1. Tamim Jabban

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

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8 Inheritance Notes Chapter 6 and AJ Chapters 7 and 8 1 Inheritance you know a lot about an object by knowing its class for example what is a Komondor? http://en.wikipedia.org/wiki/file:komondor_delvin.jpg

More information

Java Fundamentals (II)

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

Programming Exercise 14: Inheritance and Polymorphism

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

CS 251 Intermediate Programming Methods and More

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

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018 Object-oriented programming 1 and data-structures CS/ENGRD 2110 SUMMER 2018 Lecture 4: OO Principles - Polymorphism http://courses.cs.cornell.edu/cs2110/2018su Lecture 3 Recap 2 Good design principles.

More information

Making New instances of Classes

Making New instances of Classes Making New instances of Classes NOTE: revised from previous version of Lecture04 New Operator Classes are user defined datatypes in OOP languages How do we make instances of these new datatypes? Using

More information

Today. Book-keeping. Inheritance. Subscribe to sipb-iap-java-students. Slides and code at Interfaces.

Today. Book-keeping. Inheritance. Subscribe to sipb-iap-java-students. Slides and code at  Interfaces. Today Book-keeping Inheritance Subscribe to sipb-iap-java-students Interfaces Slides and code at http://sipb.mit.edu/iap/java/ The Object class Problem set 1 released 1 2 So far... Inheritance Basic objects,

More information

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017 Inheritance Lecture 11 COP 3252 Summer 2017 May 25, 2017 Subclasses and Superclasses Inheritance is a technique that allows one class to be derived from another. A derived class inherits all of the data

More information

Inheritance. A key OOP concept

Inheritance. A key OOP concept Inheritance A key OOP concept Setting the scene Why do we need inheritance? Inheritance enables you to define a new class based upon an existing class. The new class is similar to the existing class, but

More information

25. Generic Programming

25. 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 information

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

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

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. February 10, 2017

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. February 10, 2017 Inheritance and Inheritance and Pieter van den Hombergh Thijs Dorssers Stefan Sobek Fontys Hogeschool voor Techniek en Logistiek February 10, 2017 /FHTenL Inheritance and February 10, 2017 1/45 Topics

More information

Chapter 10 Classes Continued. Fundamentals of Java

Chapter 10 Classes Continued. Fundamentals of Java Chapter 10 Classes Continued Objectives Know when it is appropriate to include class (static) variables and methods in a class. Understand the role of Java interfaces in a software system and define an

More information

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED EXERCISE 11.1 1. static public final int DEFAULT_NUM_SCORES = 3; 2. Java allocates a separate set of memory cells in each instance

More information

9 Working with the Java Class Library

9 Working with the Java Class Library 9 Working with the Java Class Library 1 Objectives At the end of the lesson, the student should be able to: Explain object-oriented programming and some of its concepts Differentiate between classes and

More information

COMP200 INHERITANCE. OOP using Java, from slides by Shayan Javed

COMP200 INHERITANCE. OOP using Java, from slides by Shayan Javed 1 1 COMP200 INHERITANCE OOP using Java, from slides by Shayan Javed 2 Inheritance Derive new classes (subclass) from existing ones (superclass). Only the Object class (java.lang) has no superclass Every

More information

Exercise: Singleton 1

Exercise: 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 information

Lecture 4: Extending Classes. Concept

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

HAS-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. 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 information

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide AP Computer Science Chapter 10 Implementing and Using Classes Study Guide 1. A class that uses a given class X is called a client of X. 2. Private features of a class can be directly accessed only within

More information

1 Shyam sir JAVA Notes

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

Chapter 11 Classes Continued

Chapter 11 Classes Continued Chapter 11 Classes Continued The real power of object-oriented programming comes from its capacity to reduce code and to distribute responsibilities for such things as error handling in a software system.

More information

First IS-A Relationship: Inheritance

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

Comp 249 Programming Methodology

Comp 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

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017 Introduction to OOP with Java Instructor: AbuKhleif, Mohammad Noor Sep 2017 Lecture 11: Inheritance and Polymorphism Part 1 Instructor: AbuKhleif, Mohammad Noor Sep 2017 Instructor AbuKhleif, Mohammad

More information

Comments are almost like C++

Comments are almost like C++ UMBC CMSC 331 Java Comments are almost like C++ The javadoc program generates HTML API documentation from the javadoc style comments in your code. /* This kind of comment can span multiple lines */ //

More information

Inheritance. Transitivity

Inheritance. Transitivity Inheritance Classes can be organized in a hierarchical structure based on the concept of inheritance Inheritance The property that instances of a sub-class can access both data and behavior associated

More information

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

HAS-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. 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 information

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

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

Outline. Object-Oriented Design Principles. Object-Oriented Design Goals. What a Subclass Inherits from Its Superclass?

Outline. Object-Oriented Design Principles. Object-Oriented Design Goals. What a Subclass Inherits from Its Superclass? COMP9024: Data Structures and Algorithms Week One: Java Programming Language (II) Hui Wu Session 1, 2014 http://www.cse.unsw.edu.au/~cs9024 Outline Inheritance and Polymorphism Interfaces and Abstract

More information

CSC9T4: Object Modelling, principles of OO design and implementation

CSC9T4: Object Modelling, principles of OO design and implementation CSC9T4: Object Modelling, principles of OO design and implementation CSCU9T4 Spring 2016 1 Class diagram vs executing program The class diagram shows us a static view of the responsibilities and relationships

More information

Module 10 Inheritance, Virtual Functions, and Polymorphism

Module 10 Inheritance, Virtual Functions, and Polymorphism Module 10 Inheritance, Virtual Functions, and Polymorphism Table of Contents CRITICAL SKILL 10.1: Inheritance Fundamentals... 2 CRITICAL SKILL 10.2: Base Class Access Control... 7 CRITICAL SKILL 10.3:

More information

CS 251 Intermediate Programming Methods and Classes

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

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2 CITS2200 Data Structures and Algorithms Topic 2 Java Primer Review of Java basics Primitive vs Reference Types Classes and Objects Class Hierarchies Interfaces Exceptions Reading: Lambert and Osborne,

More information

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Covered in this chapter Classes Objects Methods Parameters double primitive type } Create a new class (GradeBook) } Use it to create an object.

More information

More about inheritance

More about inheritance Main concepts to be covered More about inheritance Exploring polymorphism method polymorphism static and dynamic type overriding dynamic method lookup protected access 4.1 The inheritance hierarchy Conflicting

More information

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. January 11, 2018

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. January 11, 2018 Inheritance and Inheritance and Pieter van den Hombergh Thijs Dorssers Stefan Sobek Java Inheritance Example I Visibility peekabo Constructors Fontys Hogeschool voor Techniek en Logistiek January 11, 2018

More information

Lecture 2: Java & Javadoc

Lecture 2: Java & Javadoc Lecture 2: Java & Javadoc CS 62 Fall 2018 Alexandra Papoutsaki & William Devanny 1 Instance Variables or member variables or fields Declared in a class, but outside of any method, constructor or block

More information

Generic Collections CSC Spring 2019 Howard Rosenthal

Generic Collections CSC Spring 2019 Howard Rosenthal Generic Collections CSC 295-01 Spring 2019 Howard Rosenthal Course References Materials for this course have utilized materials in the following documents. Additional materials taken from web sites will

More information