Object-Oriented Programming (Java)

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

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

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

Informatik II (D-ITET) Tutorial 6

What is Inheritance?

CS-202 Introduction to Object Oriented Programming

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

Chapter 5 Object-Oriented Programming

Informatik II Tutorial 6. Subho Shankar Basu

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

Classes and Inheritance Extending Classes, Chapter 5.2

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

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Chapter 7. Inheritance

ECE 122. Engineering Problem Solving with Java

Basic Object-Oriented Concepts. 5-Oct-17

C++ Important Questions with Answers

Programming Exercise 14: Inheritance and Polymorphism

Inheritance Motivation

Class, Variable, Constructor, Object, Method Questions

25. Generic Programming

EEE-425 Programming Languages (2013) 1

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

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

Create a Java project named week10

Example: Count of Points

Arrays Classes & Methods, Inheritance

CH. 2 OBJECT-ORIENTED PROGRAMMING

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

Practice for Chapter 11

ENCAPSULATION AND POLYMORPHISM

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

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

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

Inheritance. Transitivity

OBJECT ORİENTATİON ENCAPSULATİON

Chapter 4: Writing Classes

Inheritance -- Introduction

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

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Week 5-1: ADT Design

ITI Introduction to Computing II

Exercise: Singleton 1

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

Overriding Variables: Shadowing

Java Object Oriented Design. CSC207 Fall 2014

Inheritance and Polymorphism

CMSC 132: Object-Oriented Programming II. Inheritance

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

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

Lecture 4: Extending Classes. Concept

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

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

OVERRIDING. 7/11/2015 Budditha Hettige 82

Inheritance (continued) Inheritance

Introduction to Inheritance

Java Magistère BFA

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

More Relationships Between Classes

1 Shyam sir JAVA Notes

Example: Count of Points

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

Programming Language Concepts: Lecture 2

EEE-425 Programming Languages (2013) 1

ITI Introduction to Computing II

PROGRAMMING III OOP. JAVA LANGUAGE COURSE

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

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

Object Oriented Programming. Week 1 Part 3 Writing Java with Eclipse and JUnit

Software and Programming 1

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

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

Object-Oriented Programming Concepts

C08: Inheritance and Polymorphism

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Notes on Chapter Three

Programming overview

Inheritance and Polymorphism

CS 251 Intermediate Programming Inheritance

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

Encapsulation. Mason Vail Boise State University Computer Science

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

Selected Java Topics

Java Classes & Primitive Types

Chapter 6 Introduction to Defining Classes

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

First IS-A Relationship: Inheritance

Super-Classes and sub-classes

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

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

COP 3330 Final Exam Review

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

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

Class Hierarchy and Interfaces. David Greenstein Monta Vista High School

Anatomy of a Class Encapsulation Anatomy of a Method

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

Compaq Interview Questions And Answers

Rules and syntax for inheritance. The boring stuff

Inheritance and Polymorphism. CS180 Fall 2007

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

Transcription:

Object-Oriented Programming (Java)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Declare a subclass public class DerivedClass extends BaseClass { 40

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

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

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

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

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

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

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

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

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", 3000.0); 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

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

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

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", 3000.0); Animal Mammal Dog 52

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

Example Using Downcast Person person = new Employee("Joe Smith", "100 Main Ave", 3000.0); 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

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

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

Answer: Practical Quiz 3.1 57

Answer: Practical Quiz 3.2 58