SOFTWARE DEVELOPMENT 1. Objects III 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

Size: px
Start display at page:

Download "SOFTWARE DEVELOPMENT 1. Objects III 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)"

Transcription

1 SOFTWARE DEVELOPMENT 1 Objects III 2018W (Institute of Pervasive Computing, JKU Linz)

2 PRINCIPLES OF OO PROGRAMMING Data Abstraction Polymorphism Encapsulation Inheritance Program elements (objects) are changeable, meaning they can be extended restricted redefined abstracted (pool similarities, form classes) polymorphed (the same behavior can be implemented differently) Software Development 1 // 2018W // 2

3 HIERARCHICAL CLASSIFICATION Objects of the real world can be ordered in different categories, e.g. persons, animals, media, bank accounts, It seems obvious to order the world in hierarchical classes. Example: Each car is a motor vehicle, and each motor vehicle is a transport. But there are also trucks that are motor vehicles, and each train, ship or aircraft is also a transport. transport motor vehicle train ship aircraft car truck InterCity tram Software Development 1 // 2018W // 3

4 IDEA: INHERITANCE (VERERBUNG) Both cars and trucks have driver seats and doors, therefore these are properties of the superclass motor vehicle. They also have common behavior, like close door or drive, so these are also part of motor vehicle. But the subclass car also has properties and behaviors of its own, e.g. back seat, trunk, or enter in the back. Trucks have unique properties and behaviors too, e.g. cargo area, trailer or load. Subclasses (like car or truck) include all properties (fields) and behaviors (methods) of their superclass, but may have additional ones. Classes inherit fields (properties) and methods (behavior) of their superclass. Software Development 1 // 2018W // 4

5 INHERITANCE New class B is derived (abgeleitet) from the existing class A B inherits from A or B extends A B is a subclass (Unterklasse, abgeleitete Klasse) of A A is a superclass (Oberklasse) of B A B Relations between A and B B is a subclass of A B is an A (B adopts everything without limitations, conformity) B is a specialization of A (B has unique behavior), or A is generalization of B (A collects common traits) B implements A (B realizes concepts from A) B uses A (technical, B uses code from A) Advantages Common fields and methods only have to be specified once, and are easy to change later on. Software Development 1 // 2018W // 5

6 INHERITANCE IN JAVA; DIAGRAMS class A { type field; type method(... ); field: type A method(...): type class B extends A { type additionalfield; type additionalmethod(... ); Example: public class Person { public String firstname, lastname; public class Student extends Person { public int matriculationnumber; Student inherits the fields firstname and lastname, but they are not mentioned again in the diagrams. B additionalfield: type additionalmethod(...): type Person firstname: String lastname: String Student matriculationnumber: int Software Development 1 // 2018W // 6

7 WHAT IS INHERITED? Subclass inherits all fields and methods, that can be reached: All fields and methods that have been declared public or protected. If the superclass is in the same package, fields and methods without any access modifier are also inherited. Overview of access modifiers: Field/method visible for: public protected default private defining class yes yes yes yes subclass in the same package yes yes yes no subclass in another package yes yes no no different class, same package yes yes yes no different class, other package yes no no no private fields and methods are not inherited. Software Development 1 // 2018W // 7

8 INHERITANCE HIERARCHY Inheriting repeatedly produces an inheritance hierarchy. Example: Person Athlete Student Sports Student Computer Science Student Multiple inheritance: Sports Student inherits from both Athlete and Student. In Java: Multiple inheritance is not allowed. Inheritance hierarchy is a tree with Object as the root class. Interfaces mostly compensate the lack of multiple inheritance. Software Development 1 // 2018W // 8

9 INHERITANCE HIERARCHY :: EXAMPLE 3 account classes: Find common fields and methods and pool them in a single superclass CurrentAccount balance: double interestrate: double owner: Person overdraw: double CurrentAccount( owner: Person, overdraw: double) getbalance(): double deposit(amount: double) withdraw(amount: double) TimeAccount balance: double interestrate: double owner: Person runtime: int TimeAccount( owner: Person, runtime: int) getbalance(): double deposit(amount: double) withdraw(amount: double) SavingsAccount balance: double interestrate: double owner: Person mindeposit: int SavingsAccount( owner: Person, mindeposit: int) getbalance(): double deposit(amount: double) withdraw(amount: double) Software Development 1 // 2018W // 9

10 INHERITANCE HIERARCHY :: EXAMPLE Account balance: double interestrate: double owner: Person getbalance(): double deposit(amount: double) withdraw(amount: double) CurrentAccount overdraw: double CurrentAccount( owner: Person, overdraw: double) runtime: int TimeAccount TimeAccount( owner: Person, runtime: int) SavingsAccount mindeposit: int SavingsAccount( owner: Person, mindeposit: int) Software Development 1 // 2018W // 10

11 INHERITANCE HIERARCHY :: EXAMPLE public class Account { protected double balance; protected double interestrate; protected Person owner; public double getbalance() { return balance; No Constructor! Compiler generates default- Constructor, that initializes all fields with 0, null, Account balance: double interestrate: double owner: Person getbalance(): double deposit(amount: double) withdraw(amount: double) public boolean deposit(double amount) { balance += amount; return true; Methods to deposit or withdraw money. If the transfer was successful, return true. public boolean withdraw(double amount) { balance -= amount; return true; SWE1.07 / at / jku / pervasive / swe1 / vo7 / Account.java Software Development 1 // 2018W // 11

12 INHERITANCE HIERARCHY :: EXAMPLE public class CurrentAccount extends Account { private double overdraw; Superclass if specified with keyword extends. public CurrentAccount(Person owner, double overdraw) { this.owner = owner; this.overdraw = overdraw; interestrate = 2.0; balance = 0.0; New Constructor. Default-Constructor will not be generated! Account CurrentAccount overdraw: double CurrentAccount( owner: Person, overdraw: double) public boolean withdraw(double amount) { if (getbalance()-amount > overdraw) return super.withdraw(amount); else return false; Method withdraw is being overwritten. More on that later. SWE1.07 / at / jku / pervasive / swe1 / vo7 / CurrentAccount.java Software Development 1 // 2018W // 12

13 INHERITANCE HIERARCHY :: EXAMPLE public class TimeAccount extends Account { Account private int runtime; public TimeAccount(Person owner, int runtime) { this.owner = owner; this.runtime = runtime; interestrate = 4.0; balance = 0.0; Private field runtime is only visible within this class, not even in subclasses. Inherited fields from superclass Account are visible. They were declared protected. runtime: int TimeAccount TimeAccount( owner: Person, runtime: int) SWE1.07 / at / jku / pervasive / swe1 / vo7 / TimeAccount.java Software Development 1 // 2018W // 13

14 INHERITANCE HIERARCHY :: EXAMPLE public class SavingsAccount extends Account { Account private int mindeposit; public SavingsAccount(Person owner, int mindeposit) { this.owner = owner; this.mindeposit = mindeposit; interestrate = 3.0; balance = 0.0; Method deposit is being overwritten. More on that later. SavingsAccount mindeposit: int SavingsAccount( owner: Person, mindeposit: int) public boolean deposit(double amount) { if (amount > mindeposit) return super.deposit(amount); else return false; SWE1.07 / at / jku / pervasive / swe1 / vo7 / SavingsAccount.java Software Development 1 // 2018W // 14

15 ALLOWED OBJECT ASSIGNMENTS Account Person me =..., you =...; CurrentAccount TimeAccount SavingsAccount CurrentAccount mycurrentaccount; SavingsAccount mysavingsaccount; Account myaccount, youraccount; mycurrentaccount = new CurrentAccount(me, -500); mysavingsaccount = new SavingsAccount(me, 100); myaccount = mycurrentaccount; myaccount youraccount Account mycurrentaccount mysavingsaccount CurrentAccount SavingsAccount :CurrentAccount owner: Person = me overdraw = -500 :SavingsAccount owner: Person = me mindeposit = 100 Software Development 1 // 2018W // 15

16 ALLOWED OBJECT ASSIGNMENTS Account youraccount = new SavingsAccount(you, 80); CurrentAccount TimeAccount SavingsAccount //invalid: mycurrentaccount = mysavingsaccount; //invalid: mycurrentaccount = new SavingsAccount(me, 50); // assume that creating Account makes sense: myaccount = new Account(); //invalid: mycurrentaccount = myaccount; Account myaccount :Account owner = null... mycurrentaccount CurrentAccount :CurrentAccount owner: Person = me overdraw = -500 SavingsAccount Software Development 1 // 2018W // 16 youraccount mysavingsaccount :SavingsAccount owner: Person = me mindeposit = 100 :SavingsAccount owner: Person = you mindeposit = 80

17 TYPE CONVERSION OF OBJECTS Account Each CurrentAccount / SavingsAccount object is also an Account object: CurrentAccount TimeAccount SavingsAccount Therefore myaccount = mycurrentaccount; is a legal assignment. The actual object that is bound to a reference does not necessarily have to be exactly of the class the reference was declared with: It can also be of any subclass. The object is polymorph. But not every Account object is a CurrentAccount object: mycurrentaccount = myaccount; may be valid, but does not have to be! If the object referenced by myaccount is of class CurrentAccount, then the assignment is valid. If it is a SavingsAccount object, it is not! Compiler can not know of which class an object is before running the application, therefore such an assignment will produce a runtime error. Software Development 1 // 2018W // 17

18 TYPE CONVERSION OF OBJECTS Account CurrentAccount TimeAccount SavingsAccount General classes (superclasses) can be converted to specialized classes (subclasses) with a type cast: myaccount = mycurrentaccount; mycurrentaccount = (CurrentAccount)myAccount; This leads to a type check of the referenced object at runtime. If we try to convert to a class that is not valid for the referenced object, a runtime error is generated: mysavingsaccount = (SavingsAccount)myAccount; Exception in thread "main" java.lang.classcastexception: CurrentAccount cannot be cast to SavingsAccount at Account.main(Account.java:43) To check if an object is an instance of a specific class, or any subclass of this class, there is the instanceof-operator: if (myaccount instanceof SavingsAccount) mysavingsaccount = (SavingsAccount)myAccount; Software Development 1 // 2018W // 18

19 THE CLASS OBJECT If there is no explicit superclass (no extends ), then Java always assumes extends Object! Object is the superclass of all classes, the root of the class hierarchy. Some methods of Object should be overwritten appropriately: public String tostring() This method should always return a useful textual representation of the object. E.g. the println method will use tostring to convert objects to text. public boolean equals(object obj) Compares with the parameter for equality. The default implementation will just compare the references. protected Object clone() Returns an identical copy of this object. Take a look at the Java API documentation for more methods of Object. Software Development 1 // 2018W // 19

20 KEYWORD super Similar to the way this references fields, methods and constructors of the current object and class, super is used to access members of the superclass. class A { x is newly declared. A.x and B.x are different fields! int x; public A() { x = 1; class B extends A { int x; public B(int newx) { x = newx; Assign a value to B.x. If we do not explicitly call a super constructor, the default super constructor A() is called at the beginning. class C extends B { int x; public C(int x) { super(3); this.x = x; super.x += 5; ((A)this).x += 5; Call constructor of B with parameter 3; this needs be done at the beginning! x... parameter x this.x... object field of C super.x... object field of B ((A)this).x... object field of A Software Development 1 // 2018W // 20

21 OVERWRITING METHODS Methods may be newly declared in sub classes, which is called overwriting: The new method replaces the overwritten method in all subclasses. Overwritten methods can still be called with the super keyword. Watch out: Overwrite (Überschreiben) Overload (Überladen) class A { int x; public void greetme() { System.out.println("A greets you."); class B extends A { int x; public void greetme() { System.out.println("B greets you."); super.greetme(); Call method A.greetMe(). Software Development 1 // 2018W // 21

22 OVERWRITING METHODS There is an important difference between overwritten methods and fields: Which field is accessed depends on the type of the reference. Which method is called depends on the type of the referenced object. If the reference is casted, different fields are accessed, but the same method is called. class A { int x; public void greetme() { System.out.println("A greets you."); class B extends A { int x; public void greetme() { System.out.println("B greets you."); A mya = new B(); mya.x = 1; // A.x = 1 ((A)myA).x = 2; // A.x = 2 ((B)myA).x = 3; // B.x = 3 mya.greetme(); // output: B greets you. ((A)myA).greetMe(); // output: B greets you. ((B)myA).greetMe(); // output: B greets you. Software Development 1 // 2018W // 22

23 METHOD SELECTION AND BINDING Each object has its method table with all declared methods, bound by one of the two following methods: Static binding (early binding) The method is bound by the compiler during compilation. Dynamic binding (late binding) If methods are overwritten in subclasses, the compiler can no longer decide during compilation, which method needs to be called. This depends on the referenced object (type unknown during compilation), not the reference (type known). Therefore the correct method (with the correct method signature) is chosen during runtime from the method table. Software Development 1 // 2018W // 23

24 SELECTION OF METHODS 1. step - static binding: Preparation during compilation 1.1 Search for the correct method declaration belonging to the method call (check method identifier and signature) 1.2 Check access permission (depends on access modifiers in declaration) 1.3 Decide on call method: nonvirtual (static binding), if private, static or final virtual (dynamic binding) otherwise 2. step - dynamic binding: Final binding during runtime 2.1 Find target object on which the method is called 2.2 Decide on the method that needs to be called if nonvirtual: there is only one method, use this one if virtual: search for the first method with matching signature start search at class of the target object if no method matches, continue with superclass... Software Development 1 // 2018W // 24

25 EXAMPLE: INHERITANCE Overload constructor subsidy() returns the amount of subsidy a person gets. Constructors are not inherited! They need to be redeclared in each subclass. Overwrite subsidy() Person firstname: String lastname: String birthdate: Date Person(firstName: String,...) Person(p: Person) age(): int subsidy(): int studentid: int branch: String Student Student(firstName: String,...) Student(p: Person) Student(s: Student) subsidy(): int Overwrite subsidy() again income: int Tutor Tutor(firstName: String,...) Tutor(s: Student, income: int) subsidy(): int

26 EXAMPLE :: INHERITANCE public class Person { public String firstname, lastname; // name of person public Date birthdate; // date of birth public Person(String firstname, String lastname, int day, int month, int year) { this.firstname = firstname; this.lastname = lastname; birthdate = new Date(day, month, year); public Person(Person p) { // alternative constructor this(p.firstname, p.lastname, p.birthdate.day, p.birthdate.month, p.birthdate.year); public int age() { // get age of person int thisyear = Calendar.getInstance().get(Calendar.YEAR); return thisyear - birthdate.year; Overload constructor (same name and class, but different signature) public int subsidy() { // usually no subsidy is granted return 0; SWE1.07 / at / jku / pervasive / swe1 / vo7 / Person.java Software Development 1 // 2018W // 26

27 EXAMPLE :: INHERITANCE public class Student extends Person { // unique id number for next student static private int nextstudentid = ; Static field (class field) public int studentid; // unique student id number (e.g. matrikelnummer) public String branch; // study branch (e.g. "computer science") public Student(String firstname, String lastname, int day, int month, int year, String branch) { super(firstname, lastname, day, month, year); // call super constr. studentid = nextstudentid++; // assign new student id this.branch = branch; public Student(Student s) { super(s); // call super constructor studentid = nextstudentid++; // assign new student id this.branch = s.branch; Overwrite method (same name and signature, but in subclass) public int subsidy() { // students get subsidy if younger than 26 return age() < 26? 150 : 0; SWE1.07 / at / jku / pervasive / swe1 / vo7 / Student.java Software Development 1 // 2018W // 27

28 EXAMPLE :: INHERITANCE public class Tutor extends Student { public int income; // income of tutor public Tutor(String firstname, String lastname, int day, int month, int year, String branch, int income) { super(firstname, lastname, day, month, year, branch); this.income = income; public Tutor(Student s, int income) { super(s); this.income = income; Call subsidy() method from superclass Student public int subsidy() { // a tutors subsidy is reduced by his income // (but never negative) return Math.max(0, super.subsidy() - income); SWE1.07 / at / jku / pervasive / swe1 / vo7 / Tutor.java Software Development 1 // 2018W // 28

29 EXAMPLE :: INHERITANCE // test operations public static void main(string[] args) { Person p; Student s; Tutor t; p = new Person("Theo", "Kopetzky", 18, 9, 1976); s = new Student("Julia", "Maus", 29, 2, 1990, "CS"); t = new Tutor("Monika", "Hecht", 27, 3, 1991, "CS", 100); t = new Tutor(s, 120); s = null; // student becomes tutor p is of type Person and references a Person-object ("Theo") System.out.println(p.firstName + " gets: " + p.subsidy()); p = t; System.out.println(p.firstName + " gets: " + p.subsidy()); p is of type Person and references a Tutor-object ( Monika"). System.out.println(t.income); The method Tutor.subsidy() is called! if (p instanceof Tutor) System.out.println(((Tutor)p).income); t = (Tutor)p; SWE1.07 / at / jku / pervasive / swe1 / vo7 / Tutor.java Software Development 1 // 2018W // 29

30 KEYWORD final To declare fields, methods or classes as being immutable / unchangeable, state the final modifier in the declaration. Global Variables / Static Fields: Values may be assigned only once, directly with the declaration or in a static block. After that the value can never be changed (constant). According to the Java naming conventions, constant names should be in upper case, with underscores (_) to separate words. final static double PI = 3.14; Typical constants final static String THE_ANSWER = "42"; final static String[] NUMBERS = {"Zero", "One", "Two";... NUMBERS[1] = "ONE"; Warning: It is allowed to declare constants with complex data types (arrays or objects). Constant is in this case only the reference, it is not allowed to assign a different object. The object fields are not final and may be changed anytime. This assignment is therefore valid! Software Development 1 // 2018W // 30

31 KEYWORD final Object fields, parameters or local variables: Value is assigned once with the declaration, in the constructor or in the current code block. It can not be changed afterwards as long as it is valid, but fields can be different for each object instance or local variables / parameters for each method call. Using final can prevent a lot of programming errors. class Circle { final double radius; final double area; Circle(double radius) { this.radius = radius; this.area = radius * radius * Math.PI; Values may be assigned directly with the declaration or in the constructor, like here. The value will stay constant for the full object life time. static double cf(final double r) { return 2 * r * Math.PI; Parameters and local variables can also be declared as final. They will stay constant for each method call. Software Development 1 // 2018W // 31

32 KEYWORD final Methods: Final methods can not be overwritten. public final int getbalance() {... Classes: Prevents any further subclasses. Extending a final class is prohibited. public final class CurrentAccount extends Account {... All methods and fields of a final class are implicitly also final (e.g. see java.lang.string). Use final methods and classes only if necessary. It is often difficult to predict in advance why and how a class is extended later on. Software Development 1 // 2018W // 32

33 ABSTRACT METHODS AND CLASSES Problem: 2 kinds of persons: workers and employees. From both we want to get their income through a uniform interface, but it is calculated differently: Member {abstract firstname: String lastname: String getincome(): int {abstract Worker workhours: int hourincome: int getincome(): int Employee baseincome: int locationbonus: int getincome(): int We introduce the superclass Member with the common fields and methods. But since there are no actual persons / objects of the class Member, implementing the method would not make sense. Solution: The method getincome() is declared as abstract Abstract methods only have a method signature, but no body. Software Development 1 // 2018W // 33

34 ABSTRACT METHODS AND CLASSES public abstract class Member { public String firstname, lastname; public abstract int getincome(); Abstract class with method signature public class Worker extends Member { public int workhours, hourincome; public int getincome() { return workhours * hourincome; public class Employee extends Member { public int baseincome, locationbonus; 2 different implementations of getincome() public int getincome() { return baseincome + locationbonus; Software Development 1 // 2018W // 34 SWE1.07 / at / jku / pervasive / swe1 / vo7 / Member.java SWE1.07 / at / jku / pervasive / swe1 / vo7 / Worker.java SWE1.07 / at / jku / pervasive / swe1 / vo7 / Employee.java

35 ABSTRACT METHODS AND CLASSES // test operations public static void main(string[] args) { Member[] department = new Member[4]; References of abstract superclass Member department[0] = new Worker(); // 1.Member department[1] = new Employee(); // 2.Member department[2] = new Employee(); // 3.Member department[3] = new Employee(); // 4.Member New instances of Worker and Employee objects. It is impossible to instantiate Member objects! int sum = 0; // sum up all incomes for (int i = 0; i < department.length; i++) sum += department[i].getincome(); Retrieve income through common interface. Software Development 1 // 2018W // 35

36 ABSTRACT METHODS AND CLASSES An abstract method is not implemented (has no method body), it is a blueprint for derived methods. A class has to be declared abstract if any of its methods is abstract. It is allowed to declare classes as abstract, although there are no abstract methods. An abstract class can have both abstract and actual (non-abstract) subclasses. It is not possible to instantiate an abstract class, to create new objects of this class. Only objects of non-abstract subclasses can be created. Abstract methods have to be implemented in non-abstract subclasses, or the subclass has to be declared abstract itself. Software Development 1 // 2018W // 36

37 THE JAVA-MAIN METHOD :: ENTRY-POINT FOR PROGRAM EXECUTION In the Java programming language, every application must contain a main method, arbitrary placed, whose signature is: class Program { //previous methods public static void main(string[] args) { // Code in the method //following methods Modifier Return type Argument public and static can be written in either order (public static or static public), but the convention is to use public static as shown above. void see next slide The argument can be named anything you want, but most programmers choose "args" or "argv". (Runtime System passes info to the Application: java MyApp arg1 arg2) Software Development 1 // 2018W // 37

38 THE JAVA-MAIN METHOD :: ENTRY-POINT FOR PROGRAM EXECUTION Return type void of main() (Java Specification): The method main must be declared public, static, and void. It must accept a single argument that is an array of strings. A program terminates all its activity and exits when one of two things happens: All the threads that are not daemon threads terminate. Some thread invokes the exit method of class Runtime or class System and the exit operation is not forbidden by the security manager. A Java program may exit before or after the main method finishes. A return value from main would therefore be meaningless. If you want the program to return a status code, call one of the following methods (note: all three methods never return normally): System.exit(int status),runtime.exit(int status),runtime.halt(int status) Software Development 1 // 2018W // 38

39 INTERFACES Interface can be seen as fully abstract classes: Contain only abstract methods or constants. There are no actual instructions. Specify only the behavior of an object, not how it is actually implemented. Interfaces can not be instantiated. Interfaces are declared with the keyword interface instead of class, and are included in a class with implements instead of extends. Interfaces allow multiple inheritance in Java: A class may implement several interfaces. They are not an inheritance mechanism in the OO sense. Example: interface Comparable { int compareto(object o); <<interface>> Comparable compareto(object o): int Software Development 1 // 2018W // 39

40 INTERFACES :: MOTIVATION Motivation for using interfaces: To separate specification and implementation. Allows multiple inheritance. Behavior is known, but the implementation is not: An interface just specifies what a method does, not how it is done. To allow multiple, competing implementations. The basic properties are defined through the method signatures. The method signature defines its input-/output behavior: the input parameters and the return type. Interfaces can be used without knowing anything about the actual implementation (encapsulation). Software Development 1 // 2018W // 40

41 INTERFACES :: MULTIPLE INHERITANCE Multiple inheritance = a class has several superclasses Person Athlete Student Sports Student Computer Science Student Problem: What to do if names conflict? Solution: Multiple inheritance in Java not allowed, a class may only extend exactly one superclass. But: Interfaces can be used instead. Software Development 1 // 2018W // 41

42 INTERFACES Declaration: interface InterfaceName { Constants&MethodDeclarations Interface can also inherit from other interfaces (but not classes!): interface InterfaceName extends SuperInterface {... Implementation of interfaces in a class: class ClassName extends SuperClass implements Interface1, Interface2,... {... If the class does not implement all of the methods in the interface, the class needs to be declared as abstract. Software Development 1 // 2018W // 42

43 INTERFACES class B extends A implements I {... References to objects of class B can have the following data types: Class B B myb = new B(); Class A, of which B inherits A mya = (A)myB; Interface I, that B implements I myi = (I)myB; Superclasses of A, I Object myo = (Object)myB; All interface-methods are implicitly public and abstract. public, because interface methods need to be known. abstract, because interfaces do not implement the methods. All interface-fields are implicitly public, static and final Since interface can not be instantiated, fields can only be constants (static and final). Software Development 1 // 2018W // 43

44 INTERFACES :: EXAMPLE Accounting application in a corner shop: Sells different kinds of goods, e.g. food, toys, books. All goods have a description and a price. Some wares have additional properties, e.g. food has a calories information, toys have a minimum age, books have an author. Value-added tax: Food is excluded, for toys and books there are taxes. For all goods with taxes we have a tax rate and a formula to calculate the tax. Software Development 1 // 2018W // 44

45 INTERFACES :: EXAMPLE Goods is the common superclass (could also be done as abstract class) Goods description: String price: double Goods(...) display() Taxable is an interface and defines the properties and methods of all taxable goods. <<interface>> Taxable taxrate: double = 0.06 calculatetax(): double Food calories: double Food(...) display() Toy minage: int Toy(...) display() Book author: String Book(...) display() Only Toy and Book implement the interface Taxable Software Development 1 // 2018W // 45

46 INTERFACES :: EXAMPLE public class Goods { String description; double price; Base class for all goods Goods(String description, double price) { this.description = description; this.price = price; void display() { System.out.println("item: " + description); System.out.println("price: " + price); SWE1.07 / at / jku / pervasive / swe1 / vo7 / Goods.java Software Development 1 // 2018W // 46

47 INTERFACES :: EXAMPLE public class Food extends Goods { double calories; Additional field. Food(String description, double price, double calories) { super(description, price); this.calories = calories; void display() { super.display(); System.out.println("calories: " + calories); Add more output details. SWE1.07 / at / jku / pervasive / swe1 / vo7 / Food.java Software Development 1 // 2018W // 47

48 INTERFACES :: EXAMPLE public interface Taxable { double taxrate = 0.06; double calculatetax(); Interface declaration taxrate is implicitly static and final Method declaration (no Implementation) SWE1.07 / at / jku / pervasive / swe1 / vo7 / Taxable.java Software Development 1 // 2018W // 48

49 INTERFACES :: EXAMPLE public class Toy extends Goods implements Taxable { int minimumage; public Toy(String description, double price, int minimumage) { super(description, price); this.minimumage = minimumage; void display() { super.display(); System.out.println("minimum Age: " + minimumage); public double calculatetax() { return price * taxrate; Implement the method calculatetax() taxrate is implicitly static and final SWE1.07 / at / jku / pervasive / swe1 / vo7 / Toy.java Software Development 1 // 2018W // 49

50 INTERFACES :: EXAMPLE public class Book extends Goods implements Taxable { String author; public Book(String description, double price, String author) { super(description, price); this.author = author; void display() { super.display(); System.out.println("Author: " + author); public double calculatetax() { return price * taxrate; Implementation of method calculatetax(). We could also implement a different formula here. SWE1.07 / at / jku / pervasive / swe1 / vo7 / Book.java Software Development 1 // 2018W // 50

51 INTERFACES :: EXAMPLE public static void main(string[] args) { Goods[] inventory = { new Goods("Bubble Bath", 1.40), new Food("Steak", 4.45, 1500), new Book("Frost", 24.95, "Bernhard"), new Toy("Lego", 54.45, 8), new Food("Banana", 1.20, 500), new Toy("Ball", 3.90, 0) ; Create an array with different goods. Output all our goods. for (int i = 0; i < inventory.length; i++) { inventory[i].display(); if (inventory[i] instanceof Taxable) { Taxable invtax = (Taxable)inventory[i]; System.out.println("Tax: " + invtax.calculatetax()); Software Development 1 // 2018W // 51 To avoid the additional reference invtax: System.out.println("Tax: " + ((Taxable)inventory[i]).calculateTax()); If it is a taxable item, show tax too. SWE1.07 / at / jku / pervasive / swe1 / vo7 / Goods.java

52 SOFTWARE DEVELOPMENT 1 Objects III 2018W (Institute of Pervasive Computing, JKU Linz)

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

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

Handout 9 OO Inheritance.

Handout 9 OO Inheritance. Handout 9 CS603 Object-Oriented Programming Fall 2016 Page 1 of 11 Handout 9 OO Inheritance. All classes in Java form a hierarchy. The top of the hierarchy is class Object Example: classicalarchives.com

More information

Intro to Computer Science 2. Inheritance

Intro to Computer Science 2. Inheritance Intro to Computer Science 2 Inheritance Admin Questions? Quizzes Midterm Exam Announcement Inheritance Inheritance Specializing a class Inheritance Just as In science we have inheritance and specialization

More information

C# Programming for Developers Course Labs Contents

C# Programming for Developers Course Labs Contents C# Programming for Developers Course Labs Contents C# Programming for Developers...1 Course Labs Contents...1 Introduction to C#...3 Aims...3 Your First C# Program...3 C# The Basics...5 The Aims...5 Declaring

More information

Inheritance Advanced Programming ICOM 4015 Lecture 11 Reading: Java Concepts Chapter 13

Inheritance Advanced Programming ICOM 4015 Lecture 11 Reading: Java Concepts Chapter 13 Inheritance Advanced Programming ICOM 4015 Lecture 11 Reading: Java Concepts Chapter 13 Fall 2006 Adapted from Java Concepts Companion Slides 1 Chapter Goals To learn about inheritance To understand how

More information

Inheritance (P1 2006/2007)

Inheritance (P1 2006/2007) Inheritance (P1 2006/2007) Fernando Brito e Abreu (fba@di.fct.unl.pt) Universidade Nova de Lisboa (http://www.unl.pt) QUASAR Research Group (http://ctp.di.fct.unl.pt/quasar) Chapter Goals To learn about

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

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 & Abstract Classes Fall 2018 Margaret Reid-Miller

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller Inheritance & Abstract Classes 15-121 Margaret Reid-Miller Today Today: Finish circular queues Exercise: Reverse queue values Inheritance Abstract Classes Clone 15-121 (Reid-Miller) 2 Object Oriented Programming

More 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

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

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

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

Chapter Goals. Chapter 9 Inheritance. Inheritance Hierarchies. Inheritance Hierarchies. Set of classes can form an inheritance hierarchy

Chapter Goals. Chapter 9 Inheritance. Inheritance Hierarchies. Inheritance Hierarchies. Set of classes can form an inheritance hierarchy Chapter Goals To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass constructors To learn about protected and package access control To

More information

Example: Count of Points

Example: Count of Points Example: Count of Points 1 class Point { 2... 3 private static int numofpoints = 0; 4 5 Point() { 6 numofpoints++; 7 } 8 9 Point(int x, int y) { 10 this(); // calling the constructor with no input argument;

More 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: Definition

Inheritance: Definition Inheritance 1 Inheritance: Definition inheritance: a parent-child relationship between classes allows sharing of the behavior of the parent class into its child classes one of the major benefits of object-oriented

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

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass? 1. Overriding Methods A subclass can modify behavior inherited from a parent class. A subclass can create a method with different functionality than the parent s method but with the same: Name Return type

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

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

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

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

SSE3052: Embedded Systems Practice

SSE3052: Embedded Systems Practice SSE3052: Embedded Systems Practice Minwoo Ahn minwoo.ahn@csl.skku.edu Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong

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

Instance Members and Static Members

Instance Members and Static Members Instance Members and Static Members You may notice that all the members are declared w/o static. These members belong to some specific object. They are called instance members. This implies that these

More 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

More Relationships Between Classes

More Relationships Between Classes More Relationships Between Classes Inheritance: passing down states and behaviors from the parents to their children Interfaces: grouping the methods, which belongs to some classes, as an interface to

More 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

Learn more about our research, discover data science, and find other great resources at:

Learn more about our research, discover data science, and find other great resources at: Learn more about our research, discover data science, and find other great resources at: http://www.dataminingapps.com Chapter 7 Delving Further into Object- Oriented Concepts Overview Annotations Overloading

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

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

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

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

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

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

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

Lesson 14: Abstract Classes and Interfaces March 6, Object-Oriented S/W Development with Java CSCI 3381

Lesson 14: Abstract Classes and Interfaces March 6, Object-Oriented S/W Development with Java CSCI 3381 Lesson 14: Abstract Classes and Interfaces March 6, 2012 1 Object-Oriented S/W Development with Java CSCI 3381 Not all Classes do Objects Make 2 Object-Oriented S/W Development with Java CSCI 3381 Preventing

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

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

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

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

CHAPTER 10 INHERITANCE

CHAPTER 10 INHERITANCE CHAPTER 10 INHERITANCE Inheritance Inheritance: extend classes by adding or redefining methods, and adding instance fields Example: Savings account = bank account with interest class SavingsAccount extends

More information

Inheritance. Unit 8. Summary. 8.1 Inheritance. 8.2 Inheritance: example. Inheritance Overriding of methods and polymorphism The class Object

Inheritance. Unit 8. Summary. 8.1 Inheritance. 8.2 Inheritance: example. Inheritance Overriding of methods and polymorphism The class Object Unit 8 Inheritance Summary Inheritance Overriding of methods and polymorphism The class Object 8.1 Inheritance Inheritance in object-oriented languages consists in the possibility of defining a class that

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

CIS 110: Introduction to computer programming

CIS 110: Introduction to computer programming CIS 110: Introduction to computer programming Lecture 25 Inheritance and polymorphism ( 9) 12/3/2011 CIS 110 (11fa) - University of Pennsylvania 1 Outline Inheritance Polymorphism Interfaces 12/3/2011

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

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

Inheritance and Subclasses

Inheritance and Subclasses Software and Programming I Inheritance and Subclasses Roman Kontchakov / Carsten Fuhs Birkbeck, University of London Outline Packages Inheritance Polymorphism Sections 9.1 9.4 slides are available at www.dcs.bbk.ac.uk/

More information

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation COMP-202 Unit 8: Defining Your Own Classes CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation Defining Our Own Classes (1) So far, we have been creating

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

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

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

Objects and Classes. Lecture 10 of TDA 540 (Objektorienterad Programmering) Chalmers University of Technology Gothenburg University Fall 2017

Objects and Classes. Lecture 10 of TDA 540 (Objektorienterad Programmering) Chalmers University of Technology Gothenburg University Fall 2017 Objects and Classes Lecture 10 of TDA 540 (Objektorienterad Programmering) Carlo A. Furia Alex Gerdes Chalmers University of Technology Gothenburg University Fall 2017 All labs have been published Descriptions

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

CSEN401 Computer Programming Lab. Topics: Introduction and Motivation Recap: Objects and Classes

CSEN401 Computer Programming Lab. Topics: Introduction and Motivation Recap: Objects and Classes CSEN401 Computer Programming Lab Topics: Introduction and Motivation Recap: Objects and Classes Prof. Dr. Slim Abdennadher 16.2.2014 c S. Abdennadher 1 Course Structure Lectures Presentation of topics

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

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

Class, Variable, Constructor, Object, Method Questions

Class, Variable, Constructor, Object, Method Questions Class, Variable, Constructor, Object, Method Questions http://www.wideskills.com/java-interview-questions/java-classes-andobjects-interview-questions https://www.careerride.com/java-objects-classes-methods.aspx

More information

Chapter 12: Inheritance

Chapter 12: Inheritance Chapter 12: Inheritance Objectives Students should Understand the concept and role of inheritance. Be able to design appropriate class inheritance hierarchies. Be able to make use of inheritance to create

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

CSC Inheritance. Fall 2009

CSC Inheritance. Fall 2009 CSC 111 - Inheritance Fall 2009 Object Oriented Programming: Inheritance Within object oriented programming, Inheritance is defined as: a mechanism for extending classes by adding variables and methods

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

Inheritance and Polymorphism. CS180 Fall 2007

Inheritance and Polymorphism. CS180 Fall 2007 Inheritance and Polymorphism CS180 Fall 2007 Definitions Inheritance object oriented way to form new classes from pre-existing ones Superclass The parent class If class is final, cannot inherit from this

More 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

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

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

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

Chapter 9 Objects and Classes. OO Programming Concepts. Classes. Objects. Motivations. Objectives. CS1: Java Programming Colorado State University

Chapter 9 Objects and Classes. OO Programming Concepts. Classes. Objects. Motivations. Objectives. CS1: Java Programming Colorado State University Chapter 9 Objects and Classes CS1: Java Programming Colorado State University Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections, loops,

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

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

VIRTUAL FUNCTIONS Chapter 10

VIRTUAL FUNCTIONS Chapter 10 1 VIRTUAL FUNCTIONS Chapter 10 OBJECTIVES Polymorphism in C++ Pointers to derived classes Important point on inheritance Introduction to virtual functions Virtual destructors More about virtual functions

More 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

I pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class.

I pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class. Name: Covers Chapters 1-3 50 mins CSCI 1301 Introduction to Programming Armstrong Atlantic State University Instructor: Dr. Y. Daniel Liang I pledge by honor that I will not discuss this exam with anyone

More information

Polymorphism and Inheritance

Polymorphism and Inheritance Walter Savitch Frank M. Carrano Polymorphism and Inheritance Chapter 8 Objectives Describe polymorphism and inheritance in general Define interfaces to specify methods Describe dynamic binding Define and

More information

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University Lecture 3 COMP1006/1406 (the Java course) Summer 2014 M. Jason Hinek Carleton University today s agenda assignments 1 (graded) & 2 3 (available now) & 4 (tomorrow) a quick look back primitive data types

More information

ECOM 2324 COMPUTER PROGRAMMING II

ECOM 2324 COMPUTER PROGRAMMING II ECOM 2324 COMPUTER PROGRAMMING II Object Oriented Programming with JAVA Instructor: Ruba A. Salamh Islamic University of Gaza 2 CHAPTER 9 OBJECTS AND CLASSES Motivations 3 After learning the preceding

More information

A base class (superclass or parent class) defines some generic behavior. A derived class (subclass or child class) can extend the base class.

A base class (superclass or parent class) defines some generic behavior. A derived class (subclass or child class) can extend the base class. Inheritance A base class (superclass or parent class) defines some generic behavior. A derived class (subclass or child class) can extend the base class. A subclass inherits all of the functionality of

More 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

Location: Planet Laser Interview Skills Workshop

Location: Planet Laser Interview Skills Workshop Department of Computer Science Undergraduate Events Events this week Drop in Resume/Cover Letter Editing Date: Tues., Jan 19 CSSS Laser Tag Time: 12:30 2 pm Date: Sun., Jan 24 Location: Rm 255, ICICS/CS

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

Distributed Systems Recitation 1. Tamim Jabban

Distributed Systems Recitation 1. Tamim Jabban 15-440 Distributed Systems Recitation 1 Tamim Jabban Office Hours Office 1004 Sunday, Tuesday: 9:30-11:59 AM Appointment: send an e-mail Open door policy Java: Object Oriented Programming A programming

More information

Polymorphism. return a.doublevalue() + b.doublevalue();

Polymorphism. return a.doublevalue() + b.doublevalue(); Outline Class hierarchy and inheritance Method overriding or overloading, polymorphism Abstract classes Casting and instanceof/getclass Class Object Exception class hierarchy Some Reminders Interfaces

More information

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Mahmoud El-Gayyar elgayyar@ci.suez.edu.eg Ad hoc-polymorphism Outline Method overloading Sub-type Polymorphism Method overriding Dynamic

More information

OO Programming Concepts. Classes. Objects. Chapter 8 User-Defined Classes and ADTs

OO Programming Concepts. Classes. Objects. Chapter 8 User-Defined Classes and ADTs Chapter 8 User-Defined Classes and ADTs Objectives To understand objects and classes and use classes to model objects To learn how to declare a class and how to create an object of a class To understand

More information

Inf1-OP. Classes with Stuff in Common. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein.

Inf1-OP. Classes with Stuff in Common. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. Inf1-OP Inheritance UML Class Diagrams UML: language for specifying and visualizing OOP software systems UML class diagram: specifies class name, instance variables, methods,... Volker Seeker, adapting

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

Principles of Software Construction: Objects, Design and Concurrency. Polymorphism, part 2. toad Fall 2012

Principles of Software Construction: Objects, Design and Concurrency. Polymorphism, part 2. toad Fall 2012 Principles of Software Construction: Objects, Design and Concurrency Polymorphism, part 2 15-214 toad Fall 2012 Jonathan Aldrich Charlie Garrod School of Computer Science 2012 C Garrod, J Aldrich, and

More information

EXERCISES SOFTWARE DEVELOPMENT I. 09 Objects: Inheritance, Polymorphism and Dynamic Binding 2018W

EXERCISES SOFTWARE DEVELOPMENT I. 09 Objects: Inheritance, Polymorphism and Dynamic Binding 2018W EXERCISES SOFTWARE DEVELOPMENT I 09 Objects: Inheritance, Polymorphism and Dynamic Binding 2018W Inheritance I INHERITANCE :: MOTIVATION Real world objects often exist in various, similar variants Attributes

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

Example: Count of Points

Example: Count of Points Example: Count of Points 1 public class Point { 2... 3 private static int numofpoints = 0; 4 5 public Point() { 6 numofpoints++; 7 } 8 9 public Point(int x, int y) { 10 this(); // calling Line 5 11 this.x

More information

Inf1-OP. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. March 12, School of Informatics

Inf1-OP. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. March 12, School of Informatics Inf1-OP Inheritance Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein School of Informatics March 12, 2018 UML Class Diagrams UML: language for specifying and visualizing OOP software

More information

Principles of Software Construction: Objects, Design and Concurrency. Inheritance, type-checking, and method dispatch. toad

Principles of Software Construction: Objects, Design and Concurrency. Inheritance, type-checking, and method dispatch. toad Principles of Software Construction: Objects, Design and Concurrency 15-214 toad Inheritance, type-checking, and method dispatch Fall 2013 Jonathan Aldrich Charlie Garrod School of Computer Science 2012-13

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

STUDENT LESSON A5 Designing and Using Classes

STUDENT LESSON A5 Designing and Using Classes STUDENT LESSON A5 Designing and Using Classes 1 STUDENT LESSON A5 Designing and Using Classes INTRODUCTION: This lesson discusses how to design your own classes. This can be the most challenging part of

More information

Polymorphism. Object Orientated Programming in Java. Benjamin Kenwright

Polymorphism. Object Orientated Programming in Java. Benjamin Kenwright Polymorphism Object Orientated Programming in Java Benjamin Kenwright Quizzes/Labs Every single person should have done Quiz 00 Introduction Quiz 01 - Java Basics Every single person should have at least

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