PROGRAMMING III OOP. JAVA LANGUAGE COURSE

Similar documents
Intro to Enums CMSC 202

Chapter 13. Interfaces and Inner Classes

Chapter 14 Abstract Classes and Interfaces

CMSC 132: Object-Oriented Programming II

enum Types 1 1 The keyword enum is a shorthand for enumeration. Zheng-Liang Lu Java Programming 267 / 287

Interfaces. An interface forms a contract between the object and the outside world.

Another IS-A Relationship

A final method is a method which cannot be overridden by subclasses. A class that is declared final cannot be inherited.

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

Subtype Polymorphism

Interfaces (1/2) An interface forms a contract between the object and the outside world.

1 Shyam sir JAVA Notes

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

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

CMSC 132: Object-Oriented Programming II

Java Object Oriented Design. CSC207 Fall 2014

CS 251 Intermediate Programming Inheritance

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

CS-202 Introduction to Object Oriented Programming

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Lecture 2: Java & Javadoc

Wrapper Classes double pi = new Double(3.14); 3 double pi = new Double("3.14"); 4... Zheng-Liang Lu Java Programming 290 / 321

Practice for Chapter 11

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

Timing for Interfaces and Abstract Classes

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

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

Chapter 5 Object-Oriented Programming

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

CH. 2 OBJECT-ORIENTED PROGRAMMING

Classes and Methods עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון מבוסס על השקפים של אותו קורס שניתן בשנים הקודמות

Programming overview

Inheritance and Polymorphism

Making New instances of Classes

Classes and Methods גרא וייס המחלקה למדעי המחשב אוניברסיטת בן-גוריון

CLASS DESIGN. Objectives MODULE 4

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

Classes and Methods לאוניד ברנבוים המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Inheritance (continued) Inheritance

IT101. Inheritance, Encapsulation, Polymorphism and Constructors

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

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

COP 3330 Final Exam Review

Java: introduction to object-oriented features

Polymorphism and Interfaces. CGS 3416 Spring 2018

Packages Inner Classes

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

Programming Exercise 14: Inheritance and Polymorphism

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

The static keyword Used to denote fields and methods that belong to a class (but not to any particular object).

Abstract Classes and Interfaces

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

What is Inheritance?

C++ Important Questions with Answers

OVERRIDING. 7/11/2015 Budditha Hettige 82

Object Oriented Programming. Java-Lecture 11 Polymorphism

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

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

CPS 506 Comparative Programming Languages. Programming Language

Programming in C# Inheritance and Polymorphism

COS226 - Spring 2018 Class Meeting # 13 March 26, 2018 Inheritance & Polymorphism

COURSE 2 DESIGN PATTERNS

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

Building custom components IAT351

Introduction to Inheritance

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

More on Inheritance. Interfaces & Abstract Classes

a guide to an object oriented programming language Niket Sheth JAVA

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

Chapter 13 Abstract Classes and Interfaces

Rules and syntax for inheritance. The boring stuff

Chapter 13 Abstract Classes and Interfaces. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

ITI Introduction to Computing II

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

Inheritance, Polymorphism, and Interfaces

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

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

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

Sri Vidya College of Engineering & Technology

Methods Common to all Classes

Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7

C08: Inheritance and Polymorphism

Inheritance. Transitivity

Reusing Classes. Hendrik Speleers

Nested Classes in Java. Slides by: Alon Mishne Edited by: Eran Gilad, Eyal Moscovici April 2013

Majustic - Evaluation Test With Answers. Time: 1 hour 30 minutes

Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal

Super-Classes and sub-classes

Lecture Notes Chapter #9_b Inheritance & Polymorphism

CIS 110: Introduction to computer programming

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

Homework 6. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

ITI Introduction to Computing II

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

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

Motivations. Objectives. object cannot be created from abstract class. abstract method in abstract class

Programming II (CS300)

Inheritance and Polymorphism

Transcription:

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 operator Nested classes Enumerations

RELATION BETWEEN CLASSES What relation between classes exists?

RELATION BETWEEN CLASSES What relations between classes exists? Associations Dependence Association Agregation Composition Inheritance

INHERITANCE Inheritance is a mechanism which allows a class A to inherit members (data and functions) of a class B. We say A inherits from B. Objects of class A thus have access to members of class B without the need to redefine them. Terminology Base class The class that is inherited Derived class A specialization of base class Kind-of relation Class level (Circle is a kind-of Shape) Is-a relation Object level (The object circle1 is-a shape.) Types of inheritance Simple One base class Multiple - NOT SUPPORTED IN JAVA Multiple base classes

SIMPLE INHERITANCE Syntax [ClassSpecifier] class ClassName extends BaseClass {... Example public class Figure { Color color; public Figure() { this.color = Color.RED; public class Circle extends Figure { int radius; int centerx, centery;... A class inherits a single base class

SIMPLE INHERITANCE. CONSTRUCTORS super keyword Example public class Figure { Color color; public Figure() { this.color = Color.RED; public Figure (Color c) { this.color = c public String tostring(){ return color: + this.color; public class Circle extends Figure { int radius; int centerx, centery; public Circle(){ super(); public Circle (int r, int x, int y, Color c) { super(c); this. radius = r; this.centerx = x; this.centery = y; public String tostring() { return [ + this.radius +,( + this.centerx +, + this.centery + ), + super.tostring() + ] ;

ABSTRACT CLASSES Abstract classes is a class declared abstrat It may or not include abstract methods Abstract method Method that is only declared without an implementation Example: public static void foomethod(int par1); Properties Abstract classes cannot be instantiated Can contain abstract and non abstract methods Can contain fields that are not static or final All interface methods are by default public so they do not need to be declared public

INTERFACES Interfaces simlar to class API - Application Programming Interfaces a "contract" that spells out software interactions Can contain only constants method signature default methods static methods nested types Syntax [interfacemodiefier] interface InterfaceName [implements Inteface1 [,..InterfaceN]]{... where interfacemodiefier: package, public

INTEFACES

INTERFACES CAN BE EXTENDED Creation (definition) of interfaces can be done using inheritance one interface can extend another. Sometimes interfaces are used just as labeling mechanisms Look in the Java API documentation for interfaces like Cloneable or Serializable. Optional reade about Marker design pattern and annotations

INTERFACES default methods from java 8 enable the add of new functionalities to interfaces without breaking the classes that implements that interface Example interface InterfaceA { public void saysomething(); default public void sayhi() { System.out.println("Hi"); public class MyClass implements InterfaceA { @Override public void saysomething() { System.out.println("Hello World");

INTERFACES default methods Conflicts with multiple interface problem or more interfaces has a default method with the same signature solution provide implementation for the method in derived class new implementation call one of the intefaces implementation static methods from java 8 similar to default method except that can t be override in subclasses implementation

CASTING OBJECTS A object of a derived class can be cast as an object of the base class When a method is called, the selection of which version of method is run is totally dynamic overridden methods are dynamic

POLYMORPHISM A reference can be polymorphic, which can be defined as "having many forms" obj.doit(); This line of code might execute different methods at different times if the object that obj points to changes Polymorphic references are resolved at run time; this is called dynamic binding Careful use of polymorphic references can lead to elegant, robust software designs Polymorphism can be accomplished using inheritance or using interfaces

INSTANCEOF Knowing the type of an object during run time Usage object instanceof type It can be very useful when writing generalized routines that operate on objects of a complex class hierarchy It will cause a compiler error if the comparison is done with objects which are not in the same class hierarchy. Returns true if the type could be cast to the reference type without causing a ClassCastException, otherwise it is false.

NESTED CLASSES Define a class within another class. Why Use Nested Classes? It is a way of logically grouping classes that are only used in one place It increases encapsulation It can lead to more readable and maintainable code Types Static member classes Member classes Local classes Anonymous classes

NESTED CLASSES Types Static member classes is a static member of a class a static member class has access to all static methods of the parent, or top-level, class. Member classes is also defined as a member of a class is instance specific and has access to any and all methods and members, even the parent's this reference Local classes are declared within a block of code and are visible only within that block Anonymous classes is a local class that has no name

NESTED CLASSES example public class Outer { private class Inner { // inner class instance variables // inner class methods // end of inner class definition // outer class instance variables // outer class methods

PUBLIC INNER CLASSES If an inner class is marked public, then it can be used outside of the outer class In the case of a nonstatic inner class, it must be created using an object of the outer class BankAccount account = new BankAccount(); BankAccount.Money amount = account.new Money("41.99"); Note that the prefix account. must come before new The new object amount can now invoke methods from the inner class, but only from the inner class

PUBLIC INNER CLASSES In the case of a static inner class, the procedure is similar to, but simpler than, that for nonstatic inner classes OuterClass.InnerClass innerobject = new OuterClass.InnerClass(); Note that all of the following are acceptable innerobject.nonstaticmethod(); innerobject.staticmethod(); OuterClass.InnerClass.staticMethod();

INNER CLASS AND INHERITANCE Given an OuterClass that has an InnerClass Any DerivedClass of OuterClass will automatically have InnerClass as an inner class In this case, the DerivedClass cannot override the InnerClass An outer class can be a derived class An inner class can be a derived class also

ANONYMOUS CLASSES If an object is to be created, but there is no need to name the object's class, then an anonymous class definition can be used The class definition is embedded inside the expression with the new operator An anonymous class is an abbreviated notation for creating a simple local object "in-line" within any expression, simply by wrapping the desired code in a "new" expression. Anonymous classes are sometimes used when they are to be assigned to a variable of another type The other type must be such that an object of the anonymous class is also an object of the other type The other type is usually a Java interface

ANONYMOUS CLASSES Example interface Foo { void dosomething(); public class Test { public static void main (String args[]) { Foo obj = new Foo(){ void dosomething(){ System.out.println( test ); ; obj.dosomething();

ENUMERATIONS Enumerated values are used to represent a set of named values. These were often stored as constants. For example public static final int SUIT_CLUBS = 0; public static final int SUIT_DIAMONDS = 1; public static final int SUIT_HEARTS = 2; public static final int SUIT_SPADES = 3;

ENUMERATIONS number of issues with previous approach Acceptable values are not obvious Since the values are just integers, it s hard at a glance to tell what the possible values are. No type safety Since the values are just integers, the compiler will let you substitute any valid integer No name-spacing With our card example, we prefixed each of the suits with SUIT_. We chose to prefix all of those constants with this prefix to potentially disambiguate from other numerated values of the same class. Not printable Since they are just integers, if we were to print out the values, they d simply display their numerical value.

ENUMERATIONS Java 5 added an enum type to the language Declared using the enum keyword instead of class In its simplest form, it contains a commaseparatedl ist of names representing each of the possible options. public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES

ENUMERATIONS Acceptable values are now obvious must choose one of the Suit enumerated values Type safety possible values are enforced by the compiler

ENUMERATIONS Every value is name-spaced off of the enum type itself. Printing the enum value is actually readable. System.out.print("Card is a Queen of " + Suit.HEARTS);

ENUMERATIONS Additional Benefits Storage of additional information Retrieval of all enumerated values of a type Comparison of enumerated values

ENUMERATIONS. ADDITIONAL BENEFITS Enums are objects So they can have Member variables Methods For example public enum Suit { CLUBS(Color.BLACK), DIAMONDS(Color.RED), HEARTS(Color.RED), SPADES(Color.BLACK); private Color color; We could embed the color of the suit within the Suit. We can then read the value using a getter, etc. Suit(Color c) { this.color = c; public Color getcolor() { return this.color;

ENUMERATIONS. ADDITIONAL BENEFITS RETRIEVAL OF ALL ENUMERATED VALUES All enum types will automatically have a values() method that returns an array of all enumerated values for that type. Suit[ ] suits = Suit.values(); for(suit s : suits) { System.out.println(s); COMPARISON OF ENUMERATED VALUES It is possible to compare enums using the == operator. if(suit == Suit.CLUBS) { // do something can also be used with the switch control structure Suit suit = /*... */; switch (suit) { case CLUBS: case SPADES: // do something break; case HEARTS: case DIAMONDS: // do something else break; default: // yet another thing break;

COURSE TEST True or False 1. Java allows multiple inheritance 2. Abstract classes can be instantieted 3. It is imposible to declare a class inside other class 4. Inheritance is a type of polymorfis 5. From java 8 interfaces ca contain metods that are implemented in an inteface What is the usage of euals() and hashcode() methods? In which situation you need to provide a custom behaviour? (homework from previous course)