Object-Oriented Programming (Java)

Size: px
Start display at page:

Download "Object-Oriented Programming (Java)"

Transcription

1 Object-Oriented Programming (Java)

2 Topics Covered Today 2.1 Implementing Classes Defining Classes Inheritance Method equals and Method tostring 2

3 Define Classes class classname extends superclass{ type instance-variable1; type instance-variable2; // type instance-variablen; type methodname1(parameter-list){ // body of method // type methodnamen(parameter-list){ // body of method class name attribute method 3

4 Point Class class Point { private int x, y; public Point() { x=0; y=0; public Point(int x, int y) { this.x=x; this.y=y; public void move(int newx, int newy) { x = newx; y = newy; 4

5 Create Object Declare: Point p; // only variable declaration Instantiation: Use new to allocate memory for object instance, which will invoke the corresponding constructor method to initialize the values of attributes defined in a class 5

6 Creating objects of a class Point p = new Point(20,23); 0x0000 0xFF

7 Creating objects of a class Point pointone = new Point(); Point pointtwo = new Point() ; pointone = pointtwo; Before Assignment After Assignment pointone pointtwo pointone pointtwo P Q P Q 7

8 Automatic garbage collection The object P does not have a reference and cannot be used in future. The object becomes a candidate for automatic garbage collection. Java automatically collects garbage periodically and releases the memory used to be used in the future. 8

9 Accessing Object/Point Data Similar to C syntax for accessing data defined in a structure. Using object variable objectreference.variable p.x= 10; Using object method objectreference.methodname([paramlist]); p.move(30,20); 9

10 Class Diagram to JAVA Code -x : int -y : int Point public class Point { private int x; private int y; +Point() +Point(newX : int, newy : int) +getx() : int +gety() : int +setx(newx : int) +sety(newy : int) 10

11 Class Diagram to JAVA Code Point -x : int -y : int +Point() +Point(newX : int, newy : int) +getx() : int +gety() : int +setx(newx : int) +sety(newy : int) public class Point { public Point(int newx, int newy) { x = newx; y = newy; public Point(){ x = 0; y = 0; 11

12 Class Diagram to JAVA Code -x : int -y : int Point public class Point { public int getx() { return x; +Point() +Point(newX : int, newy : int) +getx() : int +gety() : int +setx(newx : int) +sety(newy : int) public int gety() { return y; 12

13 Class Diagram to JAVA Code Point -x : int -y : int +Point() +Point(newX : int, newy : int) +getx() : int +gety() : int +setx(newx : int) +sety(newy : int) public class Point { public void setx(int newx) { x = newx; public void sety(int newy) { y = newy; 13

14 Class Diagram to JAVA Code public class Point { public static void main(string[] args) { Point pointone = new Point(10, 100); System.out.println("x: " + pointone.getx()); System.out.println("y: " + pointone.gety()); pointone.setx(20); pointone.sety(200); sent message to pointone System.out.println("new x: " + pointone.getx()); System.out.println("new y: " + pointone.gety()); 14

15 Static Member Java supports definition of global methods and variables that can be accessed without creating objects of a class. Such members are called Static members. This feature is useful when we want to create a variable common to all instances of a class. One of the most common example is to have a variable that could keep a count of how many objects of a class have been created. Note: Java creates only one copy for a static variable which can be used even if the class is never instantiated. Static member of a class can be accessed by the class and objects of the class. 15

16 Static Variables Define using static: static int numberofinstances = 0; Access with the class name (ClassName.StatVarName): npoints = Point. numberofinstances; 16

17 Static Variables - Example public class Point { // class variable, one for the Point class, how many points private static int numberofinstances = 0; // Constructors... public Point(int newx, int newy) { x = newx; y = newy; numberofinstances++; public Point() { x = 0; y = 0; numberofinstances++; 17

18 Class Variables - Example public class Point { public static void main(string[] args) { Point pointone = new Point(10, 100); // numberofinstances =1 Point pointtwo = new Point(20,-200); // numberofinstances =2 pointone = new Point(10, 100); pointtwo = new Point(20,-200); numberofinstances 18

19 Instance Vs Static Variables Instance variables : One copy per object. Every object has its own instance variable. E.g. x, y Static variables : One copy per class. E.g. numberofinstances (total number of point objects created) 19

20 Static Methods A class can have methods that are defined as static (e.g., main method). Static methods can be accessed without using objects. Also, there is NO need to create objects. They are prefixed with keyword static 20

21 Static Method - Example public class Point { private static int numberofinstances = 0; public Point(int newx, int newy) { x = newx; y = newy; numberofinstances++; public Point() { x = 0; y = 0; numberofinstances++; public static int getnumberofinstances() { return numberofinstances; 21

22 Static Method - Example public class Point { public static void main(string[] args) { Point pointone = new Point(10, 100); System.out.println("x: " + pointone.getx()); System.out.println("y: " + pointone.gety()); System.out.println("Instances before PointTwo is created: " + Point.getNumberOfInstances()); Point pointtwo = new Point(20,-200); pointone.setx(20); pointone.sety(200); Point pointthree = pointone; System.out.println("new x: " + pointone.getx()); System.out.println("new y: " + pointone.gety()); System.out.println("Instances after PointTwo is created: " + Point.getNumberOfInstances()); 22

23 Output X : 10 Y : 100 New x : 20 New y : 200 Instances before PointTwo is created: 1 Instances after PointTwo is created: 2 23

24 Static main method An application requires a public static void main(string args[]) method. It must be static because, before your program starts, there aren t any objects to send messages to. public static void main(string[] args) { 24

25 Static methods restrictions They can only call other static methods. They can only access static data. They cannot refer to this or super (more later) in anyway. 25

26 Accessor and Mutator Methods An accessor method returns the current value of a variable Named getvariablename; A mutator method changes the value of a variable Named setvariablename; 26

27 Example: Getters and Setters public class BankAccount{ String accountnumber; int balance; BankAccount (String accnumber, int start){ accountnumber = accnumber; balance = start; String getaccountnumber () { return accountnumber; int getbalance () { return balance; void setbalance (int amount) { balance = balance + amount; 27

28 Encapsulation In general, instance variables should not be directly reachable by other classes using the dot (.) operator We need to build setter methods for all the instance variables in a class and find a way to force other code to call the setters rather than access the data directly. Why? By forcing other classes to call a setter method, we can protect instance variables from unacceptable changes (e.g. weight = -1) 28

29 Encapsulation An encapsulated object can be thought of as a black box -- its inner workings are hidden from the client The client invokes the interface methods of the object, which manages the instance data Client Methods Data 29

30 Visibility Modifiers In Java, we accomplish encapsulation through the appropriate use of visibility modifiers Visibility modifiers control who may access: classes methods data members Java has four visibility modifiers public protected (friendly) private 30

31 Public and Private Access public Anyone may access the item. private The item may only be accessed from the current class. 31

32 Friendly and Protected Access Friendly Access (Package local) Marked by the absence of access modifiers. The item may be accessed from anywhere within the same package. protected The item may be accessed from any subclass of the current class, or from anywhere within the same package. 32

33 Encapsulation Rule of Thumb Mark instance variables private Provide public accessors and mutators for access control 33

34 Keyword final Methods and data members can be declared final. The meaning is that a final item cannot be changed. Most common use so far: static final. 34

35 Meanings of final final variable: Value cannot be assigned anymore. final method: No subclass can override this method. final class: No class can inherit from this class. 35

36 Topics Covered Today 2.1 Implementing Classes Defining Classes Inheritance Method equals and Method tostring 36

37 Inheritance Using inheritance to implement specialization / generalization relationship in JAVA 37

38 Superclasses and Subclasses Person is called superclass or base class or parent class Employee is called subclass or derived class or child class 38

39 The is a relationship Inheritance creates an is-a relationship. Employee is a Person. Everything that can be done with a Person object can also be done with an Employee object. An Employee is a special kind of Person. It has all the functionality of a Person and some more. The subclass instances are more specific than the instances of the superclass. 39

40 Declare a subclass public class DerivedClass extends BaseClass { 40

41 Superclasses and Subclasses Any class can be both at same time e.g., Mammal is superclass of Moose and subclass of Animal Can only inherit from one superclass in Java C++ allows a subclass to inherit from multiple superclasses 41

42 Implementation of Class Person public class Person { private String name; private String address; public Person (String initialname, String initialaddress) { name = initialname; address = initialaddress; public String getname() { return this.name; public String getaddress() { return this.address; 42

43 Implementation of Class Employee public class Employee extends Person { private double salary; public Employee (String initialname, String initialaddress, double initialsalary) { super(initialname, initialaddress); salary = initialsalary; public double getsalary() { return this.salary; public void setsalary(double newsalary) { salary = newsalary; 43

44 What is Inherited? When you derive a class from a given base class: The subclass inherits all the fields of the base class It inherits all the methods of the base class You have to declare the constructors of the subclass from scratch Public fields and methods of the super-class can be used just like the fields and methods of the subclass Private fields and methods are inherited but cannot be accessed directly from the code of the subclass 44

45 Constructors Must Be Redefined Constructors of the subclass are not inherited They must be redefined in the subclass The constructor of the sub-class will normally need to use the constructor of the super-class This is done using the super keyword 45

46 Calling super(...) The first line in the constructor must be either: a call to a constructor of the super-class using super(...). A call to another constructor of the subclass using this( ). If you do not call super(...) or this(..) in the first line of the constructor, the compiler automatically places a call to the empty constructor of the superclass. If there is no empty constructor in the super-class the code will not compile! 46

47 Automatic Default Construction If we do not declare any constructor in a class then the compiler automatically adds an empty (default) constructor to it. In addition, the compiler puts in the first line of the empty constructor a call to the empty constructor of the super-class. 47

48 Using Person and Employee Classes public class test { public static void main(string[] args) { Employee e = new Employee("John","San Hao Street",1500); System.out.println("The employee name, address and salary are: " + e.getname() + "," + e.getaddress() + "," + e.getsalary()); 48

49 Person & Employee An object with the type of the subclass can be assigned to an object reference of the superclass (Upcasting) Person person = new Employee("Joe Smith", "100 Main Ave", ); The object reference of the superclass could not invoke the method defined in the subclass double salary = person.getsalary(); String name = person.getname(); String address = person.getaddress(); 49

50 Person & Employee Type conversion between Person and Employee Employee employee = (Employee) person; double salary = employee.getsalary(); or double salary = ((Employee) person).getsalary(); If the object reference points to a Person object,it can not converted to Employee Person person = new Person ("Joe Smith", "100 Main Ave"); double salary = ((Employee) person).getsalary(); 50

51 Casting Objects In Java, it is only possible to convert between superclasses and subclasses with casting. Two kinds of cast: Upcast Downcast 51

52 Upcast: Subclass Superclass Consider an object to be a parent class of the object s declared class. Always possible because substitutability is assumed. Can be implicit. Person person = new Employee("Joe Smith", "100 Main Ave", ); Animal Mammal Dog 52

53 Downcast: Superclass Subclass Consider an object to be of a subclass of its declared class. Not always possible. The type of the object to be cast is checked at runtime. Must always be explicit. Animal Mammal Dog 53

54 Example Using Downcast Person person = new Employee("Joe Smith", "100 Main Ave", ); Employee employee = (Employee) person; double salary = employee.getsalary(); Person person = new Person ("Joe Smith", "100 Main Ave"); double salary = ((Employee)person).getSalary(); JVM will throw a ClassCastException 54

55 Instanceof Operator Instanceof Operator Syntax: object instanceof ClassX Take an object reference as its first operand and a class or interface as its second operand and produces a boolean result. The instanceof operator evaluates to true if and only if the runtime type of the object is compatible with the class or interface. Use instanceof for safe casts: Person person = new Person ("Joe Smith", "100 Main Ave"); if (person instanceof Employee) { salary = ((Employee) person).getsalary(); 55

56 Review questions Visibility for class, attribute and method Usage of key word static for class, attribute, and method Usage of key word final for class, attribute, and method Why and how to do encapsulation Type conversion of object reference (Upcast and Downcast) 56

57 Answer: Practical Quiz

58 Answer: Practical Quiz

Informatik II. Tutorial 6. Mihai Bâce Mihai Bâce. April 5,

Informatik II. Tutorial 6. Mihai Bâce Mihai Bâce. April 5, Informatik II Tutorial 6 Mihai Bâce mihai.bace@inf.ethz.ch 05.04.2017 Mihai Bâce April 5, 2017 1 Overview Debriefing Exercise 5 Briefing Exercise 6 Mihai Bâce April 5, 2017 2 U05 Some Hints Variables &

More information

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

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

More information

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects CmSc 150 Fundamentals of Computing I Lesson 28: Introduction to Classes and Objects in Java 1. Classes and Objects True object-oriented programming is based on defining classes that represent objects with

More information

Informatik II (D-ITET) Tutorial 6

Informatik II (D-ITET) Tutorial 6 Informatik II (D-ITET) Tutorial 6 TA: Marian George, E-mail: marian.george@inf.ethz.ch Distributed Systems Group, ETH Zürich Exercise Sheet 5: Solutions and Remarks Variables & Methods beginwithlowercase,

More 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

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

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

Chapter 5 Object-Oriented Programming

Chapter 5 Object-Oriented Programming Chapter 5 Object-Oriented Programming Develop code that implements tight encapsulation, loose coupling, and high cohesion Develop code that demonstrates the use of polymorphism Develop code that declares

More information

Informatik II Tutorial 6. Subho Shankar Basu

Informatik II Tutorial 6. Subho Shankar Basu Informatik II Tutorial 6 Subho Shankar Basu subho.basu@inf.ethz.ch 06.04.2017 Overview Debriefing Exercise 5 Briefing Exercise 6 2 U05 Some Hints Variables & Methods beginwithlowercase, areverydescriptiveand

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

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

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable? Peer Instruction 8 Classes and Objects How can multiple methods within a Java class read and write the same variable? A. Allow one method to reference a local variable of the other B. Declare a variable

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

Chapter 7. Inheritance

Chapter 7. Inheritance Chapter 7 Inheritance Introduction to Inheritance Inheritance is one of the main techniques of objectoriented programming (OOP) Using this technique, a very general form of a class is first defined and

More information

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 6 Problem Definition and Implementation Outline Problem: Create, read in and print out four sets of student grades Setting up the problem Breaking

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

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

Programming Exercise 14: Inheritance and Polymorphism

Programming Exercise 14: Inheritance and Polymorphism Programming Exercise 14: Inheritance and Polymorphism Purpose: Gain experience in extending a base class and overriding some of its methods. Background readings from textbook: Liang, Sections 11.1-11.5.

More information

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

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

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

EEE-425 Programming Languages (2013) 1

EEE-425 Programming Languages (2013) 1 2 Learn about class concepts How to create a class from which objects can be instantiated Learn about instance variables and methods How to declare objects How to organize your classes Learn about public

More information

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed CREATED BY: Muhammad Bilal Arslan Ahmad Shaad JAVA Chapter No 5 Instructor: Muhammad Naveed Muhammad Bilal Arslan Ahmad Shaad Chapter No 5 Object Oriented Programming Q: Explain subclass and inheritance?

More information

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources. Java Inheritance Written by John Bell for CS 342, Spring 2018 Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources. Review Which of the following is true? A. Java classes may either

More information

Create a Java project named week10

Create a Java project named week10 Objectives of today s lab: Through this lab, students will examine how casting works in Java and learn about Abstract Class and in Java with examples. Create a Java project named week10 Create a package

More 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

Arrays Classes & Methods, Inheritance

Arrays Classes & Methods, Inheritance Course Name: Advanced Java Lecture 4 Topics to be covered Arrays Classes & Methods, Inheritance INTRODUCTION TO ARRAYS The following variable declarations each allocate enough storage to hold one value

More 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

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008 Overview Lecture 7: Inheritance and GUIs Written by: Daniel Dalevi Inheritance Subclasses and superclasses Java keywords Interfaces and inheritance The JComponent class Casting The cosmic superclass Object

More 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

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

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

More On inheritance. What you can do in subclass regarding methods:

More On inheritance. What you can do in subclass regarding methods: More On inheritance What you can do in subclass regarding methods: The inherited methods can be used directly as they are. You can write a new static method in the subclass that has the same signature

More information

Inheritance. Transitivity

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

More information

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 4: Writing Classes

Chapter 4: Writing Classes Chapter 4: Writing Classes Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Writing Classes We've been using predefined classes. Now we will learn to write our own

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

CS105 C++ Lecture 7. More on Classes, Inheritance

CS105 C++ Lecture 7. More on Classes, Inheritance CS105 C++ Lecture 7 More on Classes, Inheritance " Operator Overloading Global vs Member Functions Difference: member functions already have this as an argument implicitly, global has to take another parameter.

More 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

Week 5-1: ADT Design

Week 5-1: ADT Design Week 5-1: ADT Design Part1. ADT Design Define as class. Every obejects are allocated in heap space. Encapsulation : Data representation + Operation Information Hiding : Object's representation part hides,

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

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

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

Overriding Variables: Shadowing

Overriding Variables: Shadowing Overriding Variables: Shadowing We can override methods, can we override instance variables too? Answer: Yes, it is possible, but not recommended Overriding an instance variable is called shadowing, because

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

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

CMSC 132: Object-Oriented Programming II. Inheritance

CMSC 132: Object-Oriented Programming II. Inheritance CMSC 132: Object-Oriented Programming II Inheritance 1 Mustang vs Model T Ford Mustang Ford Model T 2 Interior: Mustang vs Model T 3 Frame: Mustang vs Model T Mustang Model T 4 Compaq: old and new Price:

More 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

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University Day 3 COMP 1006/1406A Summer 2016 M. Jason Hinek Carleton University today s agenda assignments 1 was due before class 2 is posted (be sure to read early!) a quick look back testing test cases for arrays

More 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

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

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch Problem Solving Creating a class from scratch 1 Recipe for Writing a Class 1. Write the class boilerplate stuff 2. Declare Fields 3. Write Creator(s) 4. Write accessor methods 5. Write mutator methods

More information

OVERRIDING. 7/11/2015 Budditha Hettige 82

OVERRIDING. 7/11/2015 Budditha Hettige 82 OVERRIDING 7/11/2015 (budditha@yahoo.com) 82 What is Overriding Is a language feature Allows a subclass or child class to provide a specific implementation of a method that is already provided by one of

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

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

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

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

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

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

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

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

Programming Language Concepts: Lecture 2

Programming Language Concepts: Lecture 2 Programming Language Concepts: Lecture 2 Madhavan Mukund Chennai Mathematical Institute madhavan@cmi.ac.in http://www.cmi.ac.in/~madhavan/courses/pl2009 PLC 2009, Lecture 2, 19 January 2009 Classes and

More information

EEE-425 Programming Languages (2013) 1

EEE-425 Programming Languages (2013) 1 2 Learn about class concepts How to create a class from which objects can be instantiated Learn about instance variables and methods How to declare objects How to organize your classes Learn about public

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

PROGRAMMING III OOP. JAVA LANGUAGE COURSE

PROGRAMMING III OOP. JAVA LANGUAGE COURSE COURSE 3 PROGRAMMING III OOP. JAVA LANGUAGE PREVIOUS COURSE CONTENT Classes Objects Object class Acess control specifier fields methods classes COUSE CONTENT Inheritance Abstract classes Interfaces instanceof

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 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. Week 1 Part 3 Writing Java with Eclipse and JUnit

Object Oriented Programming. Week 1 Part 3 Writing Java with Eclipse and JUnit Object Oriented Programming Part 3 Writing Java with Eclipse and JUnit Today's Lecture Test Driven Development Review (TDD) Building up a class using TDD Adding a Class using Test Driven Development in

More information

Software and Programming 1

Software and Programming 1 Software and Programming 1 Week 9 Lab - Use of Classes and Inheritance 8th March 2018 SP1-Lab9-2018.ppt Tobi Brodie (Tobi@dcs.bbk.ac.uk) 1 Lab 9: Objectives Exercise 1 Student & StudentTest classes 1.

More information

Inheritance. SOTE notebook. November 06, n Unidirectional association. Inheritance ("extends") Use relationship

Inheritance. SOTE notebook. November 06, n Unidirectional association. Inheritance (extends) Use relationship Inheritance 1..n Unidirectional association Inheritance ("extends") Use relationship Implementation ("implements") What is inherited public, protected methods public, proteced attributes What is not inherited

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

Object-Oriented Programming Concepts

Object-Oriented Programming Concepts Object-Oriented Programming Concepts Object-oriented programming מונחה עצמים) (תכנות involves programming using objects An object ) represents (עצם an entity in the real world that can be distinctly identified

More information

C08: Inheritance and Polymorphism

C08: Inheritance and Polymorphism CISC 3120 C08: Inheritance and Polymorphism Hui Chen Department of Computer & Information Science CUNY Brooklyn College 2/26/2018 CUNY Brooklyn College 1 Outline Recap and issues Project progress? Practice

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

Notes on Chapter Three

Notes on Chapter Three Notes on Chapter Three Methods 1. A Method is a named block of code that can be executed by using the method name. When the code in the method has completed it will return to the place it was called in

More information

Programming overview

Programming overview Programming overview Basic Java A Java program consists of: One or more classes A class contains one or more methods A method contains program statements Each class in a separate file MyClass defined 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

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

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides 1B1b Inheritance Agenda Introduction to inheritance. How Java supports inheritance. Inheritance is a key feature of object-oriented oriented programming. 1 2 Inheritance Models the kind-of or specialisation-of

More information

Encapsulation. Mason Vail Boise State University Computer Science

Encapsulation. Mason Vail Boise State University Computer Science Encapsulation Mason Vail Boise State University Computer Science Pillars of Object-Oriented Programming Encapsulation Inheritance Polymorphism Abstraction (sometimes) Object Identity Data (variables) make

More information

Classes. Classes. Classes. Class Circle with methods. Class Circle with fields. Classes and Objects in Java. Introduce to classes and objects in Java.

Classes. Classes. Classes. Class Circle with methods. Class Circle with fields. Classes and Objects in Java. Introduce to classes and objects in Java. Classes Introduce to classes and objects in Java. Classes and Objects in Java Understand how some of the OO concepts learnt so far are supported in Java. Understand important features in Java classes.

More information

Selected Java Topics

Selected Java Topics Selected Java Topics Introduction Basic Types, Objects and Pointers Modifiers Abstract Classes and Interfaces Exceptions and Runtime Exceptions Static Variables and Static Methods Type Safe Constants Swings

More information

Java Classes & Primitive Types

Java Classes & Primitive Types Java Classes & Primitive Types Rui Moreira Classes Ponto (from figgeom) x : int = 0 y : int = 0 n Attributes q Characteristics/properties of classes q Primitive types (e.g., char, byte, int, float, etc.)

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

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

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

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

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

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

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object. Inheritance in Java 1. Inheritance 2. Types of Inheritance 3. Why multiple inheritance is not possible in java in case of class? Inheritance in java is a mechanism in which one object acquires all the

More information

Class Hierarchy and Interfaces. David Greenstein Monta Vista High School

Class Hierarchy and Interfaces. David Greenstein Monta Vista High School Class Hierarchy and Interfaces David Greenstein Monta Vista High School Inheritance Inheritance represents the IS-A relationship between objects. an object of a subclass IS-A(n) object of the superclass

More information

Anatomy of a Class Encapsulation Anatomy of a Method

Anatomy of a Class Encapsulation Anatomy of a Method Writing Classes Writing Classes We've been using predefined classes. Now we will learn to write our own classes to define objects Chapter 4 focuses on: class definitions instance data encapsulation and

More information

Anatomy of a Method. HW3 is due Today. September 15, Midterm 1. Quick review of last lecture. Encapsulation. Encapsulation

Anatomy of a Method. HW3 is due Today. September 15, Midterm 1. Quick review of last lecture. Encapsulation. Encapsulation Anatomy of a Method September 15, 2006 HW3 is due Today ComS 207: Programming I (in Java) Iowa State University, FALL 2006 Instructor: Alexander Stoytchev Midterm 1 Next Tuesday Sep 19 @ 6:30 7:45pm. Location:

More information

Compaq Interview Questions And Answers

Compaq Interview Questions And Answers Part A: Q1. What are the difference between java and C++? Java adopts byte code whereas C++ does not C++ supports destructor whereas java does not support. Multiple inheritance possible in C++ but not

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

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

Method Overriding. Note that you can invoke the overridden method through the use of the keyword super.

Method Overriding. Note that you can invoke the overridden method through the use of the keyword super. Method Overriding The subclass is allowed to change the behavior inherited from its superclass, if needed. If one defines an instance method with its method name, parameters, and its return type, all identical

More information