Object Oriented (OO) Concepts with JAVA

Similar documents
Java Interview Questions and Answers

Abstract Class & Java Interface

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Fundamentals of Java Programming

Java CPD (I) Frans Coenen Department of Computer Science

History OOP languages Year Language 1967 Simula Smalltalk

Java Programming Language

Chapter 1 Java Program Design and Development

Agenda. What is and Why Polymorphism? Examples of Polymorphism in Java programs 3 forms of Polymorphism

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Description of Class Mutation Mutation Operators for Java

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

Chapter 1 Fundamentals of Java Programming

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

More on Objects and Classes

Dennis Olsson. Tuesday 31 July

Classes Dennis Olsson

AP Computer Science Java Subset

JAVA - INHERITANCE. extends is the keyword used to inherit the properties of a class. Below given is the syntax of extends keyword.

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Part I. Multiple Choice Questions (2 points each):

Java Programming Fundamentals

Java (12 Weeks) Introduction to Java Programming Language

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For

Chapter 13 - Inheritance

CS 111 Classes I 1. Software Organization View to this point:

LAB4 Making Classes and Objects

Glossary of Object Oriented Terms

Java Application Developer Certificate Program Competencies

java Features Version April 19, 2013 by Thorsten Kracht

What is Java? Applications and Applets: Result of Sun s efforts to remedy bad software engineering practices

C++ INTERVIEW QUESTIONS

CIS 190: C/C++ Programming. Polymorphism

CS193j, Stanford Handout #10 OOP 3

The Interface Concept

Object Oriented Design

Introduction to Programming Block Tutorial C/C++

Object-Oriented Programming: Polymorphism

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Object-Oriented Programming Lecture 2: Classes and Objects

Software Engineering Techniques

Tutorial on Writing Modular Programs in Scala

Java is an Object-Oriented Language. As a language that has the Object Oriented feature, Java supports the following fundamental concepts:

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

Inheritance, overloading and overriding

Moving from CS 61A Scheme to CS 61B Java

PHP Object Oriented Classes and objects

Crash Course in Java

Android Application Development Course Program

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

Programmation 2. Introduction à la programmation Java

CMPT 183 Foundations of Computer Science I

TECHNOLOGY Computer Programming II Grade: 9-12 Standard 2: Technology and Society Interaction

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Lecture 7 Notes: Object-Oriented Programming (OOP) and Inheritance

Compiling Object Oriented Languages. What is an Object-Oriented Programming Language? Implementation: Dynamic Binding

Advanced Data Structures

I. INTRODUCTION. International Journal of Computer Science Trends and Technology (IJCST) Volume 3 Issue 2, Mar-Apr 2015

Unit Testing. and. JUnit

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

JAVA - OBJECT & CLASSES

D06 PROGRAMMING with JAVA

Part 3: GridWorld Classes and Interfaces

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

Multiple Dispatching. Alex Tritthart WS 12/13

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

Using Inheritance and Polymorphism

An Overview of Java. overview-1

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

Java EE Web Development Course Program

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

Specialized Programme on Web Application Development using Open Source Tools

Polymorphism. Why use polymorphism Upcast revisited (and downcast) Static and dynamic type Dynamic binding. Polymorphism.

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

Object-Oriented Programming in Java

Syllabus for CS 134 Java Programming

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Habanero Extreme Scale Software Research Project

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

Java Programming. Binnur Kurt Istanbul Technical University Computer Engineering Department. Java Programming. Version 0.0.

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Web Development in Java

AP Computer Science A - Syllabus Overview of AP Computer Science A Computer Facilities

TypeScript for C# developers. Making JavaScript manageable

DIPLOMADO DE JAVA - OCA

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program.

Object Oriented Programming with Java. School of Computer Science University of KwaZulu-Natal

Curriculum Map. Discipline: Computer Science Course: C++

Johannes Sametinger. C. Doppler Laboratory for Software Engineering Johannes Kepler University of Linz A-4040 Linz, Austria

Génie Logiciel et Gestion de Projets. Object-Oriented Programming An introduction to Java

3 Improving the Crab more sophisticated programming

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Transcription:

Object Oriented (OO) Concepts with JAVA MSc Induction Tutorials 2011 Stefan Stafrace PhD Student Computing Department s.stafrace@surrey.ac.uk 1

What is OO Programming? Programming paradigm How a solution to a problem is formulated in a programming language Other paradigms: procedural, functional, declarative, etc Based on objects (or classes of objects) and their relationships Fundamental OO concepts include: Encapsulation, Inheritance, Polymorphism and Abstraction Other concepts include: Method Overriding and Overloading Packages and Interfaces 2

RECAP 3

Objects and Classes (1) What is a Software Object? Conceptually similar to real world objects Contains fields (state) and methods (behaviour) Benefits of using software objects Modularity The source code of an object can be written independently of the source code of other objects Code reuse If an object already exists, you can use it in your own code Debugging ease If an object contains a bug, it can be unplugged from the system and replaced with a functioning object part replacement concept 4

Objects and Classes (2) What is a Class? A class is the blueprint from which individual objects are created In OO terms, we say that an object is an instance of a class of objects 5

Encapsulation What is Encapsulation (aka data hiding)? Hide the internal state whilst all interaction is done through the object s methods All fields are declared private Use of Getter and Setter methods Benefits of encapsulation Shields the internal state from random external access Allows for state (or field) validation Fields can be read-only or write-only Details of the internal implementation are hidden from the outside world Encapsulated fields can be modified without affecting dependant code 6

Inheritance (1) What is Inheritance? The process by which a class acquires the properties of another class Classes can inherit the state and behaviour of other classes Each class is allowed to have one superclass (aka single inheritance) and each superclass can have multiple subclasses 7

Inheritance (2) class MountainBike extends Bicycle { // New fields and methods go here The subclass MountainBike inherits all the fields and methods from class Bicycle The developer can focus on the properties that make MountainBike unique 8

Inheritance (3) Keyword instanceof Operator that can determine whether a class is the subclass of another class IS-A vs. HAS-A relationship Inheritance represents an IS-A relationship where an object is a type of another object Composition is instead a HAS-A relationship whereby a class is made up from other classes E.g. The Car class is composed of various other classes such as Engine class, Wheel class, Battery class, etc 9

Overriding an inherited method (1) A subclass can override an inherited method i.e. override the functionality of any existing method Provided it is not marked as final Why would you override a method? It gives you the ability to define a behaviour that s specific to the subclass type You can use the @Override annotation that instructs the compiler that you intend to override a method in the super class 10

Overriding an inherited method (2) class Animal{ public void move(){ System.out.println("Animals can move"); class Dog extends Animal{ public void move(){ System.out.println("Dogs can walk and run"); public class TestDog{ public static void main(string args[]){ Animal a = new Animal(); // Animal reference and object Animal b = new Dog(); // Animal reference but Dog object a.move();// runs the method in Animal class b.move();//runs the method in Dog class 11

Overriding an inherited method (3) Rules for overriding The argument list should be exactly the same as that of the overridden method. The return type should be the same or a subtype of the return type declared in the original overridden method in the super class. The access level cannot be more restrictive than the overridden method's access level. Instance methods can be overridden only if they are inherited by the subclass. A method declared final cannot be overridden. A method declared static cannot be overridden but can be re-declared. Constructors cannot be overridden. 12

Overriding an inherited method (4) Invoking a super class version of an overridden method Use the super reserved word class Animal{ public void move(){ System.out.println("Animals can move"); class Dog extends Animal{ public void move(){ super.move(); // invokes the super class method System.out.println("Dogs can walk and run"); public class TestDog{ public static void main(string args[]){ Animal b = new Dog(); // Animal reference but Dog object b.move();//runs the method in Dog class 13

Overriding an inherited method (5) Overriding vs. Overloading Different methods with these same name but a different number of parameters for example: int add(int pvalue1, int pvalue2) double add(double pvalue1, double pvalue2) Overloading makes the code more readable Java compiler determines which method is used based on the method signature QUESTION: If a subclass overloads a super class method is it the same as overriding? 14

Polymorphism (1) What is polymorphism? From Greek origin: The ability of an object to take on many forms public class Shape { public class Circle extends Shape { public class Square extends Shape { Using the IS-A relationship A shape can be a circle or a square We use virtual method invocation to take advantage of polymorphism 15

Polymorphism (2) public class Shape { public double area(){ System.out.println( No shape defined"); return 0.0; public class Circle extends Shape{ final static double pi = 3.14; double radius; public double area(){ System.out.println( Circle area: + (pi*(radius^2)) ); return pi*(radius^2); public class Square extends Shape{ double length; public double area(){ System.out.println( Square area: + (length^2) ); return pi*(radius^2); 16

Polymorphism (3) public class TestVMI { public static void main(string[] args){ Shape shape = new Shape(); Shape circle = new Circle(); Shape square = new Square(); shape.area(); circle.area(); square.area(); Java compiler checks that the Shape object has a method called area() JVM invokes the appropriate method according to the reference type of the object instance (aka reference variable) 17

Abstraction (1) What is Abstraction? In OOP, it is the ability to make a class abstract An abstract class can contain fields, constructors and methods; however, it cannot be instantiated, but can be subclassed An abstract class can contain abstract methods i.e. methods that do not have an implementation Any child class must either override the abstract method or declare itself abstract. So what is the use of an abstract class? An abstract class can implement common functionality found in its subclasses; however still have some methods that are different and therefore not implemented. E.g. Shape vs. Circle or Square 18

Abstraction (2) In Java, we use the reserved word abstract to declare a class or a method as abstract public abstract class Shape { int x, y; public void moveto(int newx, int newy) { public abstract double area(); public abstract void draw(); public class Circle extends Shape{ final static double pi = 3.14; double radius; public double area(){ System.out.println( Circle area: + (pi*(radius^2)) ); return pi*(radius^2); 19

Abstraction (3) An abstract class may have static fields and static methods. You can use these static members with a class reference E.g. AbstractClass.staticMethod() - as you would with any other class Abstract classes vs. Interfaces What s the difference? You should tell me by the end of this tutorial 20

Interfaces (1) What is an interface? Generally, it is defined as a collection of abstract methods that define an object s interface with the outside world In Java, it is a reference type that can contain only constants, method signatures and nested types (inner classes) It is not a class, but they do share some similarities: An interface can contain any number of methods An interface is written in a file with a.java extension, with the name of the interface matching the name of the file The bytecode of an interface appears in a.class file Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name 21

Understanding Interfaces (2) Interfaces vs. Classes - how are they different? You cannot instantiate an interface An interface does not contain any constructors All of the methods in an interface are abstract An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final An interface is not extended by a class; it is implemented by a class. An interface can extend multiple interfaces. 22

Declaring Interfaces (3) public interface operatecar { // constant declarations, if any // method signatures int changelanes(direction direction, double startspeed, double endspeed); int signalturn(direction direction, boolean signalon);... // more method signatures To declare an interface in Java, we obviously use the keyword interface An interface is implicitly abstract Each method in an interface is also implicitly abstract Methods in an interface are implicitly public. 23

Implementing Interfaces (4) public class OperatePorsche implements OperateCar { // the OperateCar method signatures, with implementation // for example: int signalturn(direction direction, boolean signalon) { //code to turn indicator lights on A class uses the implements keyword to implement an interface The keyword appears in the class declaration following the extends portion of the declaration A class can extend only one class, but implement many interfaces Closest we get to multiple inheritance An interface can be used as a type 24

Interfaces as a Type (5) Example of using an interface as a type: public interface Relatable { // this (object calling islargerthan) and // other must be instances of the same class // returns 1, 0, -1 if this is greater // than, equal to, or less than other public int islargerthan(relatable other); public Object findlargest(object object1, Object object2) { Relatable obj1 = (Relatable)object1; Relatable obj2 = (Relatable)object2; if ( (obj1).islargerthan(obj2) > 0) return object1; else return object2; 25

Extending Interfaces (6) public interface Sports { public void sethometeam(string name); public void setvisitingteam(string name); public interface Football extends Sports { public void hometeamscored(int points); public void visitingteamscored(int points); An interface can extend another interface The extends keyword is used to extend an interface The child interface inherits the methods of the parent interface An interface can extend more than one parent interface In contrast with with the class hierarchy, where a class can extend only one class 26

Packages (1) What is a Package? A Package can be defined as a grouping of related types, such as classes and interfaces, providing access protection and name space management Packages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, etc easier Existing packages in Java are: java.lang - bundles the fundamental classes java.io - classes for input and output functions A programmer can create his/her own packages 27

Packages (2) Creating a new package Choose a name for the package and It is common practice to use lowercase names to avoid any conflicts with the names of classes, interfaces, etc Put a package statement with that name at the top of every source file that contains the classes and interfaces that you want to include in the package. package graphics; public abstract class Shape { public class Circle extends Shape{ 28

Packages (3) Naming a package It is likely that many programmers will use the same name for different types E.g. java.awt.circle vs. graphic.circle Fully qualified name avoids ambiguity What happens if two independent programmers use the same name for their packages? We use naming convention to avoid this situation Companies use their reversed Internet domain name to begin their package names Packages in the Java language itself begin with java. or javax Use an underscore for domain names that are invalid for package names 29

Packages (4) Using a package member The types that comprise a package are known as the package members How do use a public package member from outside its package? Refer to the member by its fully qualified name Import the package member Import the member's entire package Apparent hierarchy of packages For instance: java.awt package, java.awt.color package and java.awt.font package The java.awt.color and java.awt.font packages are NOT INCLUDED in the java.awt package 30

Packages (5) Name ambiguities If a member in one package shares its name with a member in another package and both packages are imported, you must refer to each member by its qualified name Static imports To reference a static final fields, you prefix the field with the class name E.g. Math.PI In case you need frequent access to static final fields (constants) and static methods from one or two classes Avoid cluttered code by using import static java.lang.math.pi Use static import very sparingly 31

Packages (6) The name of the package must match the directory structure where the corresponding class file (bytecode) resides E.g. graphics.circle.java should reside in Windows location C:\<project_path>\graphics (in UNIX, use a forward slash (/)) Always remember the CLASSPATH variable! To display the current CLASSPATH variable: In Windows -> C:\> set CLASSPATH In Unix -> % echo $CLASSPATH To delete the current contents of the CLASSPATH variable: In Windows -> C:\> set CLASSPATH= In Unix -> % unset CLASSPATH; export CLASSPATH To set the CLASSPATH variable: In Windows -> set CLASSPATH=C:\users\stefan\java\classes In Unix -> % CLASSPATH=/home/stefan/java/classes; export CLASSPATH 32

References SUN Java Trail Learning the Java Language http://java.sun.com/docs/books/tutorial/java/toc.html Tutorials Point - Java Tutorial http://www.tutorialspoint.com/java/index.htm 33

The End Questions? Comments? Thoughts? 34