Inheritance Inheritance 3/3/2014. We have already seen. Object Oriented Programming: Inheritance (Chapter 9) Abstractions

Size: px
Start display at page:

Download "Inheritance Inheritance 3/3/2014. We have already seen. Object Oriented Programming: Inheritance (Chapter 9) Abstractions"

Transcription

1 Object Oriented Programming: Inheritance (Chapter 9) Sharma Chakravarthy Information Technology Laboratory (IT Lab) Computer Science and Engineering Department The University of Texas at Arlington, Arlington, TX Course URL: wweb.uta.edu/faculty/sharmac URL: We have already seen Abstractions Focus on commonalities among objects in your system is a vs. has a vs. uses a (inheritance, aggregation/composition, dependence) is a Inheritance subclass object treated as superclass object Example: Car is a vehicle Vehicle properties/behavior are also car properties/behavior However, a vehicle is not necessarily a car! 2 Inheritance Inheritance Software reusability less development time, better model of the real world Create new subclasses from existing classes (specialization) Absorbs existing class s members (data and behavior) Enhance with new capabilities (specialization) Subclass extends a superclass (Java keyword) Subclass (subset of the superclass) More specialized group of objects Behavior inherited from superclass» Can customize Add additional behavior In Project 3, we have several groups of people who Share some common properties and behavior Users also share some properties and behavior with the above, if not all! 3 4 1

2 5 6 UML (12.3 and 13.3, 9 th ed) UML for a class Consists of A box containing (in this order): Class name and whether it is abstract, concrete, or interface All attributes with type, visibility, class or instance, initial value if any, final specification (if applicable) All constructors using the right notation (<< >>) All methods with visibility, class or instance, final specification (if applicable), parameters, and return type + for public, for private, # for protected, and ~ for default (or package private), / for derived Underline class/static attributes and methods Include <<class>>, <<abstract>> or <<interface>> as appropriate next to name UML: Links and associations A Link is the basic relationship among objects. It is represented as a line connecting two or more class boxes. A link is an instance of an association. In other words, it creates a relationship between two classes. The UML representation of an association is a line with an optional arrowhead (or diamond) filled/hollow indicating the role of the object(s) in the relationship, and an optional notation at each end indicating the multiplicity of instances of that entity (the number of objects that participate in the association) No instances, or one instance (optional, may) 1 Exactly one instance 0.. * or * Zero or more instances 1.. * One or more instances (at least one) min.. max Cardinality specification 2

3 UML for the Date class UML: Links and associations <<interface>> +DateConstants ABNORMAL_EXIT : int BASE_INDEX: int FIRST_MONTH :int... <<class>> +Date final DAYS[] : int final LEAP_YEAR : int final NON_LEAP_YEAR : int month : int day : int year : int <<constructor>> Date(m,d,y : int) <<constructor>> Date(sDate : String) <<constructor>> Date(y : int) <<constructor>> Date(m,y : int) isvalid(m,d,y : int) : boolean isleapyear(y : int) : boolean isleapmonth(m,y : int) : boolean + next() : Date + isafter(b : Date) : boolean + isbefore(b : Date) : boolean + compareto(b : Date) : int + addmonths(m : int) : Date + monthsbetween(enddate : Date) : int + daysbetween(enddate : Date) : int + tostring() : String An interface that is implemented by a class is shown with a broken (or dotted) line with an arrow at the interface box Specification inside the interface box is very similar to the class box Realization is a relationship between the blueprint class and the object containing its respective implementation level details. This object is said to realize the blueprint class. In other words, you can understand this as the relationship between the interface and the implementing class. UML: Abstraction, Generalization and realization Abstraction: specifying the framework and hiding the implementation level information. Concreteness will be built on top of the abstraction. It is a blue print for following the implementation details. Abstraction reduces complexity. In the UML diagram, specify a class to be abstract (as {abstract) Generalization represented by a is a relationship from a specialization to the generalization class. Common structure and behavior are grouped from the specialization to the generalized class. At a broader level you can understand this as inheritance. In the UML diagram an arrow goes from specialization to generalization UML: uses a relationship Uses a or dependence relationship indicates that the process of doing x always involves doing Y at least once (or many times). It is also called executes relationship Represented as a solid arrow. Dependence in terms of usage Order object uses Account object Student object uses Course object to check for registered courses 3

4 UML: Aggregation and composition Aggregation is a variant of the "has a" or association relationship; aggregation is more specific than association. It is an association that represents a part whole or part of relationship. As a type of association, an aggregation can be named and have the same adornments that an association can. However, an aggregation may not involve more than two classes. Aggregation can occur when a class is a collection or container of other classes, but where the contained classes do not have a strong life cycle dependency on the container essentially, if the container is destroyed, its contents are not. In UML, it is graphically represented as a hollow diamond shape on the containing class end of the tree with lines that connect contained classes to the containing class. Class A contains 1 or more class B objects A 1.. * B UML: Aggregation and composition(2) Aggregation differs from ordinary composition in that it does not imply ownership. In composition, when the owning object is destroyed, so are the contained objects. In aggregation, this is not necessarily true. For example, a university owns various departments (e.g., chemistry), and each department has a number of professors. If the university closes, the departments will no longer exist, but the professors in those departments will continue to exist. Therefore, a University can be seen as a composition of departments, whereas departments have an aggregation of professors. In addition, a Professor could work in more than one department, but a department could not be part of more than one university. University owns Department Has Professor A P * Composition Aggregation UML: Links and associations Composition is a stronger variant of the "owns a" or association relationship; composition is more specific than aggregation. Composition usually has a strong life cycle dependency between instances of the container class and instances of the contained class(es): If the container is destroyed, normally every instance that it contains is destroyed as well. (Note that a part can (where allowed) be removed from a composite before the composite is deleted, and thus not be deleted as part of the composite.) The UML graphical representation of a composition relationship is a filled diamond shape on the containing class end of the tree of lines that connect contained class(es) to the containing class. Superclasses and Subclasses Superclasses and subclasses Example: Rectangle is a quadrilateral Class Rectangle inherits from class Quadrilateral Quadrilateral: superclass Rectangle: subclass Superclass typically represents larger set of objects than subclasses (subset superset relationship) Example: superclass: Vehicle» Cars, trucks, boats, bicycles, subclass: Car» Smaller, more specific subset of vehicles 16 4

5 Inheritance Class hierarchy (terminology) Direct superclass Inherited explicitly (one level up hierarchy) Indirect superclass Inherited two or more levels up hierarchy Single inheritance Inherits from only one superclass Multiple inheritance Inherits from multiple superclasses Java does not support multiple inheritance (unlike C++) All classes are inherited from the Object class in Java (root of the hierarchy) 17 Superclasses and Subclasses (Cont.) Inheritance hierarchy Inheritance relationships: tree like structure why is it a tree and not a graph? Each class becomes a superclass Supplies data/behavior to subclasses (note plural) OR subclass Inherits data/behavior from a super class (note singular) in Java 18 Access modifier (for class members) public protected No modifier (packageprotected) private Scope of Inheritance (external scope) Inheritance Are inherited by any derived class Are inherited by derived classes in the same package and derived classes outside the package. Are inherited only by derived classes in the same package Scope Can be directly accessed in derived subclasses, classes in the same package, classes in other packages; Can be directly accessed by classes in the same package ; cannot be directly accessed by code outside the package (even if inherited). Can be directly accessed by classes in the same package Are inherited only by But, cannot be accessed directly in derived classes in the any other class same package Note that the above is for BOTH methods and attributes!!! 19 Scope of Inheritance (external scope) Access modifier Inheritance Scope no arg constructor (constructor without args) constructor with args (user defined) Not inherited Not inherited Implicitly invoked by subclass constructors need to be explicitly invoked with super as the first statement in the subclass constructors A default constructor is different from the no-arg constructor. The default constructor (which is also no-arg) is supplied by Java. A no-arg constructor is defined by the user. The above determines what is visible in a super class and what is visible in a subclass (both attributes and methods) The above is used by JVM to invoke (or access) appropriate methods (or attributes) Show some examples on the board! 20 5

6 External Scope Java Supports 3 external scopes That means, Java allows class members to be accessed from Derived classes Members of the same package Code external to the package External scope public protected Default private (package) Same package Yes Yes Yes No Derived class in another package Yes Yes (inheritance only) User Code (any class) Yes No No no No no package yours public class Enemy { A public member may still be hidden by a declaration of the same name in another class. Reference to a hidden member can still be done using dot notation! Public Access package mine public class Example { public int empid; public class SubExample extends Example { class Friend { Protected Access Package private Access package yours package mine package yours package mine public class Enemy { public class Example { protected int empid; class Friend { public class Enemy { public class Example { int empid; class Friend { public class SubExample2 extends Example { public class SubExample extends Example { public class SubExample2 extends Example { public class SubExample extends Example { // empid is inherited by this // class // empid is not inherited by // this class

7 package yours public class Enemy { public class SubExample2 extends Example { // empid is not inherited by // this class Private Access package mine public class Example { private int empid; // empid is visible or //accessible only in this //class public class SubExample extends Example { // empid is not inherited // by this class class Friend { // empid is not visible // from here What is inherited in a subclass A subclass (whether in the same package or not) inherits all the public and protected members of its parent If the subclass is in the same package as its parent, it also inherits the package private members (i.e., no access modifier specification) of the parent You can use inherited members in several ways: i) as is, ii) override them, iii) hide them, iv) overload them, or v) supplement the class with new members Remember, members here refer to fields and methods, but not constructors (they have their own inheritance rules) Private members in a super class A subclass cannot directly access the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can be used by the subclass. A nested class has access to all the private members of its enclosing class both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass. A nested class can be used to implement pure composition relationship (think about it!) 27 Subclasses, constructors, and attributes Class Employee { //simplified person class private String name; private double salary; public Employee(){ Name = Doe ; //empty string salary = 100.0; public Employee(String aname, double asal){ name = aname; salary = asal; public String tostring(){ return String.format( %s\t%d\n, name, salary); 28 7

8 Subclasses, Constructors, and attributes (2) Class Manager extends Employee { //simplified manager class private double bonus; public Manager(){ bonus = 0; public Manager(String aname, double asal){ super(aname, asal); //cannot assign to Employee attrs! Why? bonus = 10.0; //super call has to be the first stmt? Why? public String tostring(){ return String.format( %s\t%d, super.tostring(), bonus); public static void main(string[], myargs){ Manager m1 = new Manager(); System.out.println(m1); Manager m2 = new Manager( john, ); System.out.println(m2); Employee e1 = new Employee( Mary, ); System.out.println(e1); e1 = m2; //is this correct? System.out.println(e1); m2 = e1; // is this correct? What will be printed? Doe John Mary John Subclasses and methods Class Employee { //simplified person class private String name; private double salary; public Person(String aname, double asal){ name = aname; salary = asal; public string getname(){ return name; public double getsalary(){ return salary; //does not return anything; modifies the object called on public void raisesalary(double percent){ double raise = salary * percent/100; salary = raise; 30 Subclasses and methods (2) Class Manager extends Employee { //simplified manager class private double bonus; public Manager(String aname, double asal){ super(aname, asal); //I cannot assign to Employee attrs! Why? bonus = 0; //super call has to be the first stmt? Why? Subclasses and methods (3) Class Manager extends Employee { //simplified employee class private double bonus; public Manager(String aname, double asal){ super(aname, asal); bonus = 0; public void setbonus(double abonus){ bonus = abonus; // I can directly set this! Why? Suppose, you want to compute the salary of the manager as Employee salary + bonus. You write the following method in the manager class Public double getsalary(){ return salary + bonus; // accessing the salary field of the super classs Will this work? If it does not work, how will you make it work? 31 public void setbonus(double abonus){ bonus = abonus; Suppose, you want to compute the salary of the manager as Employee salary + bonus. You write the following method in the manager class Public double getsalary(){ double basesalary = getsalary(); //accessing super class method return basesalary + bonus; Will this work? If it does not work, how will you make it work? 32 8

9 How to invoke superclass methods Many a times you want to invoke superclass methods from the subclass even if they are overridden. If a method x() is overridden in the subclass, the parent version can be invoked explicitly from the subclass using super.x(); Note: If no overriding, super.x() is automatically invoked by the JVM when you invoke X() (this is polymorphism!) If overridden, super.x() can be explicitly invoked from within the body of the overridden X() in the subclass (closest nested scope rule applies here as well) 33 Defining subclasses (4) Class Manager extends Employee { //simplified employee class private double bonus; public Manager(String aname, double asal){ super(aname, asal); bonus = 0; public void setbonus(double abonus){ bonus = abonus; Suppose, you want to compute the salary of the manager as Employee salary + bonus. You write the following method in the manager class Public double getsalary(){ double basesalary = super.getsalary(); //accessing the method //of the super class return basesalary + bonus; Will this work? super is not the same as this. this can be used as a final variable. super cannot be (it is a mechanism) 34 Overriding and hiding When a method (signature, not a method name) of a superclass is redefined in a subclass, it is called overriding (not overloading) Note that signature has to be identical here also! If an attribute of a superclass is redefined in a subclass, it is called hiding Both are legal and have implications for visibility. Please understand them clearly! What can you do in a subclass (field) The inherited fields (based on the access modifiers used) can be used directly, just like any other fields You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it (not recommended). You can declare new fields in the subclass that are not in the superclass (specialization)

10 What can you do in a subclass (method) The inherited methods can be used directly as they are (using the keyword super) Assumes they are not overridden; is available in the subclass as is You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it (this is not overloading!) You can write a new static method in the subclass that has the same signature as the static method in the superclass, thus hiding it (compile time decision). What can you do in a subclass (method) You can declare new methods in the subclass that are not in the superclass (supplement) You can overload a method of the superclass by changing its signature; it becomes a supplement and has nothing to with inheritance!! You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or explicitly by using the keyword super. You cannot override a static method with an instance method You cannot override an instance method with a static method Constructing objects and printing Class Person { //simplified employee class private String name; //attribute/filed of the class private double salary; private Date dob; public Person(String aname, double asal, String adob){ name = aname; salary = asal; dob = new Date(aDob); public Person(String aname, double asal, Date adob){ name = aname; salary = asal; dob = adob; public String tostring(){ return [ +name+, +salary+, +dob+ ] ; public String tostring() { //taken from Date class return (" + month + -" + day + -" + year + )"; Defining subclasses (2) Class Manager extends Person { //simplified manager class private double bonus; public Manager(String aname, double asal, Date dob){ super(aname, asal, dob);//i cannot assign to Employee attrs! Why? bonus = 0; //super call has to be the first stmt? Why? public void setbonus(double abonus){ bonus = abonus; // I can directly set this! Why? public String tosting(){ return super.tostring() + (Bonus: + bonus+ ) ;

11 Constructing objects and passing parameters Suppose you want to format the output Class Test { public static void main(string[] args){ Employee emp1, emp2; //local variables Date date; //local variable emp = new Employee( john, , ); date = new Date ( ); emp3 = new Employee( Albert, , date); System.out.println(emp); System.out.println(emp2); Manager mgr = new Manager( Mary, , new Date( ); System.out.println(mgr); [john, ,( )] [Albert, ,( )] [Mary, ,( )] (Bonus: 0.0) Class Employee { //simplified employee class private String name; //attribute/filed of the class private double salary; private Date dob; public Employee(String aname, double asal, String adob){ name = aname; salary = asal; dob = new Date(aDob); public Employee(String aname, double asal, Date adob){ name = aname; salary = asal; dob = adob; public String tostring(){ return String.format( [%10s, %10.2d, %s, name, salary, dob] ; public String tostring() { //taken from Date class return String.format( (%2d-%2d-%4d, month, day. year + )"; Constructing objects and passing parameters Class Test { public static void main(string[] args){ Employee emp, emp2, emp3; //local variables Date date; //local variable emp = new Employee( john, , ); emp2 = new Employee( mary, , new Date( )); date = new Date ( ); emp3 = new Employee( Albert, , date); System.out.println(emp); System.out.println(emp2); System.out.println(emp3); //there is also System.out.format(format, params); [ john, ,( )] [ mary, ,( )] [ Albert, ,( )] 43 Passing parameters In OOP, objects are passed when a method is invoked. With the object, all fields are also passed Some of you are passing unnecessary parameters Class MavInvest{ String name; ArrayList<Employee> emps; // declares emps; does not create an //array list public MavInvest(String aname){ name = aname; emps = new ArrayList<Employee>(); //create array list public void addemployee(employee anemp){ //MavInvest object is //passed as part of class emps.add(anemp) //could also be this.emps.add(anemp); public void prettydisplay(){ for (Employee e; emps) return \n + e + \n ; Should not be passing emps as it is already passed with the object

12 Constructing objects and passing parameters Class MavInvestTest { public static void main(string[] args){ MavInvest mavinvest; Employee emp; Date date; mavinvest = new MavInvest( mavinvest enterprises ); emp = new Employee( john, , 8/6/1970 ); emp2 = new Employee( mary, , new Date( 8/7/1980 )); date = new Date ( 12/1/1991 ); emp3 = new Employee( Albert, , date); mavinvest.addemployee(emp); mavinvest.addemployee (emp2); mavinvest.addemployee(emp3); Abstract Class Java has the notion of an abstract class It is like any other class; However You cannot directly instantiate an object of an abstract class You can extend it (i.e., form subclasses both abstract and concrete) i.e., an abstract class can act as a superclass You can have fields in that class (both instance and static/class) You can have methods both abstract and concrete Abstract methods are not implemented; act as specifications mavinvest.prettydisplay(); [john, ,(8/6/1970)] [mary, ,(8/7/1980)] [Albert, ,(12/1/1991)] Of course, you can declare variables of that class/type Even though you cannot instantiate that class! (for polymorphism) Abstract method An abstract method is a method that is declared in a superclass but not implemented in that class It has to be overridden in a subclass An abstract method has only a header (includes signature, no body) AccessSpecifier abstract returntype methodname(parameterlist); The keyword abstract appears in the header The header ends with a semicolon; no braces! public abstract double computesalary(int salaryparameter); When an abstract method appears in a class/interface, it must be overridden in its subclass When a class contains an abstract method, you cannot instantiate an object of that class why? Abstract class What is the purpose? An abstract class represents the generic or abstract properties that can be inherited It can specify generic/common properties, and specify behavior that need to be implemented by subclasses It can also implement some behavior Typically abstract classes form the root of a class hierarchy Abstract classes represent design!! AccessSpecifier abstract class ClassName For example, Person (in project 3) is an abstract class It captures generic properties and behavior of a Person collector, maintainer and monitor are concrete classes extended from the person class Should user be a subclass of Person class?

13 Abstract Attributes Can we declare an attribute to be abstract? No! Why can t an attribute be abstract? Class being abstract means it cannot be instantiated! Note that an abstract class should have at least one abstract method Method being abstract means it is a specification and it should be implemented in the concrete subclass However, it is not clear what an abstract attribute is! An attribute is not implemented An attribute (both class and instance) is instantiated when the subclass object is constructed Object construction with inheritance When an object of a subclass is constructed (using a constructor), will it create: One object that contains both subclass and superclass attributes Creates two objects: one for subclass and one for superclass Creates more than two objects (as a spare)! Only one object is created which contains all the instance attributes of the subclass and all the attributes of the superclass Remember that the attributes of the superclass (or this subclass) includes attributes from all superclasses (direct or indirect) due to inheritance However, the type of the object will be both itself and it superclass (meta data maintained with each object) However, their direct usage is subject to visibility specifications Constructing objects and passing parameters public abstract class Person implements Proj3Constants { private static int nextid = ZEROI; private String firstname; private String lastname; private Date dob; private enum gender {MALE, FEMALE private int pid; public Person(String fname, String lname){ //constructor firstname = fname; lastname = lname; pid = nextid; nextid++; public String getfirstname(){ return first_name; public abstract int getageinyears(); //abstract method //when you are overriding a method, it is better to //indicates override; compiler checks and makes sure public String tostring(){ return (String.format("%7s %s, SSN: %d", firstname, lastname, pid)); 51 Casting Objects An object of type subclass is also an object of type superclass (due to is a relationship) An object of type superclass is not necessarily an object of subclass ( is a does not work in reverse) A subclass reference can be assigned to a superclass variable (polymorphism and dynamic binding are needed for exactly this reason) If you want to assign a superclass reference to a subclass variable, you must use a cast (which will be checked at runtime) An object of any class is also an object of type Object (Object is a super class of every class) 52 13

14 Casting Objects (2) Let Person be a superclass and Client its subclass Person[] persons = new Person[6];//creates an array; not //an instance of Person which is an abstract class Client aclient = new Client(); Person aperson;//ok, but Person cannot be instantiated (abstract) Now, I can write persons[1] = aclient;//ok. because Client is-a Person However, aclient = persons[1]; // is an error at compile time Person is not necessarily a Client You have to say aclient = (Client) persons[1]; // compiler will allow, but // adds a runtime check Why allow? Why runtime check? 53 Casting Objects (3) Finally, the compiler will not let you make a cast if there is no chance for the cast to succeed. Date adate = (Date) persons[1]; Is a compile time error because Date is not a subclass of Person To sum up: You can cast only within an inheritance hierarchy You can use instanceof (an operator not a method returns true/false) to check before casting from a superclass to subclass String s = Hello ; If (s instanceof java.lang.string){ //class name System.out.println( is a string ); 54 Casting Objects (4) A Client is a descendent of class Person (which is a descendent of class Object) Therefore a Client is a Person; also an Object. And Client object can be used where ever Person or Object is used. An object of any class is also an object of type Object The reverse is not necessarily true: a Person may be a Client, but it is not necessarily Similarly, an Object may be a Person or a Client, but not necessarily If I declare a variable of type Object, I can assign any object of any type to that variable //called unsafe in java Casting Objects (5) Casting shows the use of an object of one type in place of another type, among the objects permitted by inheritance and implementations (interface). A compiler knows the type of the object as defined; hence the error given is based on compile time information. Even if it is correct at compile time, this does not mean that there will not be a runtime error. However, at runtime, JVM will check the actual type of object stored in a variable and makes decisions

15 Casting Objects (6) For example, if we write Object aclient = new Client(); then aclient is of type Object and the assignment is ok as Client is a subclass of Object. This is called implicit casting. Can I write, Client myclient = aclient; We will get a compile-time error because aclient is not known to the compiler as a Client type (but known as an Object type). However, Client myclient = (Client) aclient; // is OK This cast inserts a runtime check that aclient is assigned a Client so that the compiler can safely assume that aclient is a Client If aclient is not a Client at runtime, an exception will be thrown 57 Casting Objects (7) You can make a logical test as to the type of a particular object using the instanceof operator. This can save you from a runtime error owing to an improper cast. For example: if ( aclient instanceof Client) { //lowercase of Client myclient = (Client)aClient; Here the instanceof operator verifies that aclient refers to a Client type so that we can make the cast with the knowledge that there will be no runtime exception thrown. instanceof is a keyword in Java; A variable with a null is not an object of any type 58 Instance Methods An instance method in a subclass with the same signature, (name, plus the number, order, and the type of its parameters) and a compatible return type as that of an instance method in the superclass overrides the superclass's method. The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and compatible return type as the method it overrides. An overriding method can also return a subtype of the type returned by the overridden method. This is called a covariant return type. 59 Instance Methods (2) When overriding a method, you might want to use annotation that instructs the compiler that you intend to override a method in the superclass. If, for some reason, the compiler detects that the method does not exist in one of the superclasses, it will generate an error. For more information see annotations of double getsalary(){ double basesalary = getsalary(); //won t work return basesalary + bonus; If you want to call an instance method of the superclass, use super.getsalary(); Otherwise, an infinite method call will result and the stack will overflow eventually! 60 15

16 Class Methods If a subclass defines a class method (static) with the same signature as a class method in the superclass, the method in the subclass hides the one in the superclass The distinction between hiding and overriding has important implications. The version of the overridden method that gets invoked is based on runtime information. The version of the hidden method that gets invoked is based on compile time information Remember, class methods are invoked using classname.classmethod or classmethod (not using an instance) 61 Overriding and hiding Example public class Animal { public static void testclassmethod() { System.out.println("The class method in Animal."); public void testinstancemethod() { System.out.println("The instance method in Animal."); The second class, a subclass of Animal, is called Cat: public class Cat extends Animal { public static void testclassmethod() { System.out.println("The class method in Cat."); //hides superclass method public void testinstancemethod() { System.out.println("The instance method in Cat."); // overrides superclass method public static void main(string[] args) { Cat mycat = new Cat(); Animal myanimal = mycat; //this is fine! Animal.testClassMethod(); //calling using class name mycat.testclassmethod(); // what method is invoked? Cat.testClassMethod(); myanimal.testclassmethod(); myanimal.testinstancemethod(); //myanimal has a Cat object mycat.testinstancemethod(); Cat.testInstanceMethod(); myanimal.testinstancemethod(4); // gives compilation error; why? 62 Overriding and hiding Example (2) The Cat class overrides the instance method in Animal and hides the class method in Animal. The main method in this class creates an instance of Cat and calls testclassmethod() on the class and testinstancemethod() on the instance. The output from this program is as follows: The class method in Animal. The class method in Cat. The class method in Cat. The class method in Animal. The instance method in Cat. The instance method in Cat. Preventing overriding of methods When a method is declared with the final modifier, it cannot be overridden in a subclass. Public final void message(); If a subclass tries to override a final method, the compiler generates an error This can be used to make sure that a particular superclass method is used by subclasses as is and not a modified version Methods that are declared private are implicitly final final modifier meaning is the same for class, method, and fields (that they cannot be modified). String is an example of a final class in Java

17 Method modifiers The access specifier/modifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the superclass can be made public, but not private, in the subclass. A is superclass and B is a subclass of A class A: public void X() class B: private void X() //can have arguments //gives a syntax error class A: protected void Y() class B: public void Y() //is allowed class B: private void Y() //gives a syntax error Summary The following table summarizes what happens when you define a method with the same signature as a method in a superclass. Defining a Method with the Same Signature as a Superclass's Method Subclass Instance Method Subclass Static Method Superclass Instance Method Overrides superclass method Generates a compiletime error Superclass Static Method Generates a compiletime error Hides the superclass method Note: In a subclass, you can still overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass methods they are new methods, unique to the subclass Class hierarchy of Java collections framework Abstract collection AbstractList AbstractSet AbstractQueue AbstractSequ entialist AbstractMap HashSet TreeSet HashMap TreeMap Constructors A constructor is a special method of a class If not defined, Java provides a default one with no arguments and instance fields are initialized to [0, false, null] Note that static fields are not initialized by a constructor; they are usually initialized at the point of declaration or using the static block of a class. Note that they should not be initialized in a constructor! Note that there is no return type specified (cannot even specify, unlike a method) for a constructor; it is implicitly defined to be the type of the class; the name of the constructor is also pre determined PriorityQueue ArrayQueue If a constructor is made private, it cannot even be invoked from a subclass! LinkedList ArrayList The purpose of a constructor is to initialize the instance fields of an object during its creation before returning that object

18 Constructors (2) If you write a constructor for a class, Java no longer provides the default constrictor The above is important when you have inheritance. The default super class constructor is invoked automatically unless you invoke one explicitly Hence it is Important to provide a no arg constructor if you define a constructor in a class that can act as a superclass! If there is no default or no arg constructor, you will get an error when compiling a subclass (unless there is an explicit invocation of a constructor) It is a good practice to define a no arg constructor when you define an arg constructor in a class A superclass constructor should be invoked as the first statement of the constructor. Why? 69 Constructor execution Instantiating a subclass (or any) object begins a chain of constructor calls in which the (sub)class constructor invokes its direct superclass's constructor either explicitly via the super reference or Implicitly by calling the superclass s Default constructor (if none provided by user) //what is the difference No arg constructor (if provided by the user) // between these two? The superclass constructor in turn calls the default or noargument constructor of its parent Until the constructor of the Object class is called Then the body of the original subclass constructor is executed When you have inheritance, a chain of constructors are always called 70 Constructor execution (2) Each class's constructor is responsible for manipulating/initializing the data members of its own class Do not use a constructor to manipulate data members of another class Note: Java ensures that even if a constructor does not assign a value to an instance variable, the variable is still initialized to its default value 0 -- primitive numeric types false -- booleans null -- references Note that static attributes are not initialized by the constructor! 71 Constructor execution (3) public class SuperClass { public SuperClass(){ System.out.println ( This message is from the + no-arg constructor of SuperClass ); public class SubClass extends SuperClass{ public SubClass(){ System.out.println( This msg is from the + no-arg constructor of SubClass ); public static void main(string[] args){ SubClass sc = new SubClass(); This message is from the no arg constructor of SuperClass This msg is from the no arg constructor of SubClass 72 18

19 Constructor execution (4) public class A { String name; int age; //note package access modifiers //no constructor defined //Java provides a default constructor public String tostring(){ return "from object A: [ " + name + "," + age + "]\n"; Since there is no constructor defined by user for this class, Java provides a default which is always a no argument constructor 73 Constructor execution (5) class B extends A{ private double salary; public B() { salary = 0.0; (1)//understand what happens here public B(double as){ (2) salary = as; //what are the values of name and age? public B(double as, String an){ (3) salary = as; name = an; //what are the values of name and age? public B(String an, int age, double as){ (4) super(an, age); salary = as; //what happens here? public double getsalary(){ //does this override? return salary; public String tostring(){ // does this override? return "from object B: [ " + name + "," + age + "," + getsalary() + "]\n"; 74 Constructor execution (6) class C extends B{ //sub sub class private int numkids; private String name; //hiding name from A public C(){ super( ); numkids = 2; public C(double sal, int nkids, String aname){ super(sal); //otherwise, B() is called automatically numkids = nkids; //what happens here? super.name = aname; //what happens here? name = "Henry"; // what happens here? public String tostring(){ return "from object C: [ " + super.name + "," + name + "," + age + "," + getsalary() + "," + numkids + "]\n"; Constructor execution (7) public static void main(string[] args){ C testc = new C(); System.out.println(testC); testc = new C(239.0, 3, "Mary"); System.out.println(testC); B testb = new B(); System.out.println(testB); testb = new B(555.0); System.out.println(testB); testb = new B(666.0, "Potter"); System.out.println(testB); A testa = new A(); System.out.println(testA); Output: from object C: [null, null, 0, , 2] from object C: [Mary, Henry, 0, 239.0, 3] from object B: [null, 0, 0.0] from object B: [null, 0, 555.0] from object B: [Potter, 0, 666.0] from object A: [null, 0]

20 Using super to access overridden and hidden methods and fields Super(); // call the default constructor of the superclass super(scanner in); // call user-defined superclass constructor someint = super.someint; //references a hidden field of a superclass //(must be accessible) super.instancemethod(); // call to overridden instance method in // the superclass; what about the object? super.classmethod(); // call to a hidden class method in the //superclass superclassname.classmethod(); // another way to call the class //method, without using super 77 Constructor summary The superclass constructor is always executed before the subclass constructor You can write a super statement in the subclass constructor and only in the subclass s constructor. You cannot call superclass constructor from any other method If a super statement that calls a superclass constructor appears in a subclass constructor, it must be the first statement If a subclass constructor does not explicitly call a superclass constructor, Java will automatically call super() as the first statement If a superclass does not have a default constructor and does not have a no arg constructor, then the class that inherits from it must call one of the constructors that the superclass has Provide a no arg constructor whenever you define a arg constructor! 78 Common errors to avoid Attempting to access a private superclass member directly from a subclass Forgetting to call a superclass constructor explicitly when the superclass does not have a default constructor or programmer defined no arg constructor Allowing the superclass s no arg constructor to be implicitly called when you intend to call another superclass constructor Forgetting to preceded a call to an overridden superclass method with the keyword super Common errors to avoid (2) Forgetting a class member s access specifies Results in package access; any method in that package can access the member Writing a body for an abstract method Forgetting to terminate an abstract method s header with a semicolon Failing to override an abstract method Overloading an abstract method instead of overriding it! annotation to catch this) Instantiating an abstract class

21 9.8 Object Class All classes in Java inherit directly or indirectly from Object, so its 11 methods are inherited by all other classes. Figure 9.12 summarizes Object s methods. Can learn more about Object s methods in the online API documentation and in The Java Tutorial at java.sun.com/javase-/6/docs/api/java/lang/object.html or java.sun.com/docs/books/tutorial/java/iandi/objectclass.html Every array has an overridden clone method that copies the array. If the array stores references to objects, the objects are not copied a shallow copy is performed. For more information about the relationship between arrays and class Object, see Java Language Specification, Chapter 10, at Arrays have an overridden clone() method that copies an array; but it is still a shallow copy. java.sun.com/docs/books/jls/third_edition/html/arrays.html boolean equals() is the same as == operator for comparing 2 objects

22 Thank You! 85 22

1/17/2014. UML Help and Details (from: UML for cse UML for a class. UML and project clarifications

1/17/2014. UML Help and Details (from:   UML for cse UML for a class. UML and project clarifications UML Help and Details (from: http://enwikipediaorg/wiki/class_diagram) Sharma Chakravarthy Information Technology Laboratory (IT Lab) Computer Science and Engineering Department The University of Texas

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

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2)

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2) Summary: Chapters 1 to 10 Sharma Chakravarthy Information Technology Laboratory (IT Lab) Computer Science and Engineering Department The University of Texas at Arlington, Arlington, TX 76019 Email: sharma@cse.uta.edu

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

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

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

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

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

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

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

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

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Marenglen Biba (C) 2010 Pearson Education, Inc. All Inheritance A form of software reuse in which a new class is created by absorbing an existing class s members and enriching them with

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

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

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616 OBJECT ORIENTED PROGRAMMING Course 4 Loredana STANCIU loredana.stanciu@upt.ro Room B616 Inheritance A class that is derived from another class is called a subclass (also a derived class, extended class,

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

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

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages Preliminaries II 1 Agenda Objects and classes Encapsulation and information hiding Documentation Packages Inheritance Polymorphism Implementation of inheritance in Java Abstract classes Interfaces Generics

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

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

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

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

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Argument 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 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

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

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

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

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 4&5: Inheritance Lecture Contents What is Inheritance? Super-class & sub class The object class Using extends keyword @override keyword

More information

1- Differentiate between extends and implements keywords in java? 2- What is wrong with this code:

1- Differentiate between extends and implements keywords in java? 2- What is wrong with this code: 1- Differentiate between extends and implements keywords in java? 2- What is wrong with this code: public double getsalary() double basesalary = getsalary(); return basesalary + bonus; 3- What does the

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

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

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism Block 1: Introduction to Java Unit 4: Inheritance, Composition and Polymorphism Aims of the unit: Study and use the Java mechanisms that support reuse, in particular, inheritance and composition; Analyze

More information

CS 112 Programming 2. Lecture 06. Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism

CS 112 Programming 2. Lecture 06. Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism CS 112 Programming 2 Lecture 06 Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism rights reserved. 2 Motivation Suppose you want to define classes to model circles, rectangles, and

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming 1. What is object-oriented programming (OOP)? OOP is a technique to develop logical modules, such as classes that contain properties, methods, fields, and events. An object

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

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

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

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8. OOPs Concepts 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8. Type Casting Let us discuss them in detail: 1. Data Hiding: Every

More 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

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

Practice for Chapter 11

Practice for Chapter 11 Practice for Chapter 11 MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) Object-oriented programming allows you to derive new classes from existing

More information

ENCAPSULATION AND POLYMORPHISM

ENCAPSULATION AND POLYMORPHISM MODULE 3 ENCAPSULATION AND POLYMORPHISM Objectives > After completing this lesson, you should be able to do the following: Use encapsulation in Java class design Model business problems using Java classes

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

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully

More information

Inheritance (Outsource: )

Inheritance (Outsource: ) (Outsource: 9-12 9-14) is a way to form new classes using classes that have already been defined. The new classes, known as derived classes, inherit attributes and behavior of the pre-existing classes,

More 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

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

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

The software crisis. code reuse: The practice of writing program code once and using it in many contexts. Inheritance The software crisis software engineering: The practice of conceptualizing, designing, developing, documenting, and testing largescale computer programs. Large-scale projects face many issues:

More 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

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College CISC 3115 TY3 C09a: Inheritance Hui Chen Department of Computer & Information Science CUNY Brooklyn College 9/20/2018 CUNY Brooklyn College 1 Outline Inheritance Superclass/supertype, subclass/subtype

More information

Big software. code reuse: The practice of writing program code once and using it in many contexts.

Big software. code reuse: The practice of writing program code once and using it in many contexts. Inheritance Big software software engineering: The practice of conceptualizing, designing, developing, documenting, and testing largescale computer programs. Large-scale projects face many issues: getting

More 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

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code COMPUTER SCIENCE DEPARTMENT PICNIC Welcome to the 2016-2017 Academic year! Meet your faculty, department staff, and fellow students in a social setting. Food and drink will be provided. When: Saturday,

More 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

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance Handout written by Julie Zelenski, updated by Jerry. Inheritance is a language property most gracefully supported by the object-oriented

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

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia Object Oriented Programming in Java Jaanus Pöial, PhD Tallinn, Estonia Motivation for Object Oriented Programming Decrease complexity (use layers of abstraction, interfaces, modularity,...) Reuse existing

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

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 05: Inheritance and Interfaces MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Inheritance and Interfaces 2 Introduction Inheritance and Class Hierarchy Polymorphism Abstract Classes

More information

Java Magistère BFA

Java Magistère BFA Java 101 - Magistère BFA Lesson 3: Object Oriented Programming in Java Stéphane Airiau Université Paris-Dauphine Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 1 Goal : Thou Shalt

More information

Object Oriented Programming. Java-Lecture 11 Polymorphism

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

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

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

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

Accelerating Information Technology Innovation

Accelerating Information Technology Innovation Accelerating Information Technology Innovation http://aiti.mit.edu Cali, Colombia Summer 2012 Lesson 09 Inheritance What is Inheritance? In the real world: We have general terms for objects in the real

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

Inheritance (Deitel chapter 9)

Inheritance (Deitel chapter 9) Inheritance (Deitel chapter 9) 1 2 Plan Introduction Superclasses and Subclasses protected Members Constructors and Finalizers in Subclasses Software Engineering with Inheritance 3 Introduction Inheritance

More information

Classes and Inheritance Extending Classes, Chapter 5.2

Classes and Inheritance Extending Classes, Chapter 5.2 Classes and Inheritance Extending Classes, Chapter 5.2 Dr. Yvon Feaster Inheritance Inheritance defines a relationship among classes. Key words often associated with inheritance are extend and implements.

More information

Declarations and Access Control SCJP tips

Declarations and Access Control  SCJP tips Declarations and Access Control www.techfaq360.com SCJP tips Write code that declares, constructs, and initializes arrays of any base type using any of the permitted forms both for declaration and for

More information

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

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

Rules and syntax for inheritance. The boring stuff

Rules and syntax for inheritance. The boring stuff Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for

More 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

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

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

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

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

CONSTRUCTOR & Description. String() This initializes a newly created String object so that it represents an empty character sequence.

CONSTRUCTOR & Description. String() This initializes a newly created String object so that it represents an empty character sequence. Constructor in Java 1. What are CONSTRUCTORs? Constructor in java is a special type of method that is used to initialize the object. Java constructor is invoked at the time of object creation. It constructs

More information

Inheritance and Interfaces

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

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity. OOPS Viva Questions 1. What is OOPS? OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a collection of objects. Each object is nothing but an instance of a class.

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

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

Relationships 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 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

Basic Object-Oriented Concepts. 5-Oct-17

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

Polymorphism Part 1 1

Polymorphism Part 1 1 Polymorphism Part 1 1 What is Polymorphism? Polymorphism refers to a programming language s ability to process objects differently depending on their data type or class. Number person real complex kid

More information

Announcement. Agenda 7/31/2008. Polymorphism, Dynamic Binding and Interface. The class will continue on Tuesday, 12 th August

Announcement. Agenda 7/31/2008. Polymorphism, Dynamic Binding and Interface. The class will continue on Tuesday, 12 th August Polymorphism, Dynamic Binding and Interface 2 4 pm Thursday 7/31/2008 @JD2211 1 Announcement Next week is off The class will continue on Tuesday, 12 th August 2 Agenda Review Inheritance Abstract Array

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

Advanced Placement Computer Science. Inheritance and Polymorphism

Advanced Placement Computer Science. Inheritance and Polymorphism Advanced Placement Computer Science Inheritance and Polymorphism What s past is prologue. Don t write it twice write it once and reuse it. Mike Scott The University of Texas at Austin Inheritance, Polymorphism,

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

Self-review Questions

Self-review Questions 7Class Relationships 106 Chapter 7: Class Relationships Self-review Questions 7.1 How is association between classes implemented? An association between two classes is realized as a link between instance

More information

Inheritance Motivation

Inheritance Motivation Inheritance Inheritance Motivation Inheritance in Java is achieved through extending classes Inheritance enables: Code re-use Grouping similar code Flexibility to customize Inheritance Concepts Many real-life

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

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

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

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1 Polymorphism Part 1 What is Polymorphism? Polymorphism refers to a programming language s ability to process objects differently depending on their data type or class. Number person real complex kid adult

More information

Object Oriented Programming: Based on slides from Skrien Chapter 2

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

CS1150 Principles of Computer Science Objects and Classes

CS1150 Principles of Computer Science Objects and Classes CS1150 Principles of Computer Science Objects and Classes Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Object-Oriented Thinking Chapters 1-8

More information

Atelier Java - J1. Marwan Burelle. EPITA Première Année Cycle Ingénieur.

Atelier Java - J1. Marwan Burelle.  EPITA Première Année Cycle Ingénieur. marwan.burelle@lse.epita.fr http://wiki-prog.kh405.net Plan 1 2 Plan 3 4 Plan 1 2 3 4 A Bit of History JAVA was created in 1991 by James Gosling of SUN. The first public implementation (v1.0) in 1995.

More information

Chapter 11 Inheritance and Polymorphism

Chapter 11 Inheritance and Polymorphism Chapter 11 Inheritance and Polymorphism 1 Motivations OOP is built on three principles: Encapsulation (classes/objects, discussed in chapters 9 and 10), Inheritance, and Polymorphism. Inheritance: Suppose

More information

CS111: PROGRAMMING LANGUAGE II

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