Overview of OOP in Java Tessema M. Mengistu Department of Computer - - PowerPoint PPT Presentation

overview of oop in java
SMART_READER_LITE
LIVE PREVIEW

Overview of OOP in Java Tessema M. Mengistu Department of Computer - - PowerPoint PPT Presentation

Overview of OOP in Java Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale tessema.mengistu@siu.edu Room - 3131 1 Outline Java Basics Classes and Objects Encapsulation Inheritance


slide-1
SLIDE 1

Overview of OOP in Java

1

Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale tessema.mengistu@siu.edu Room - 3131

slide-2
SLIDE 2

Outline

  • Java Basics
  • Classes and Objects
  • Encapsulation
  • Inheritance
  • Polymorphism

2

slide-3
SLIDE 3

Java Program Structure

  • Java is a pure object oriented language
  • Everything is written within a class block.

[Documentation] [package statement] [import statement(s)] [interface statement(s)] [class definition(s)] main method class definition

3

slide-4
SLIDE 4

Java Program Structure

// this is a java program import java.lang.*; class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } }

4

slide-5
SLIDE 5

Java Program Structure

  • Java program = Comments + Token(s) +

white space

  • Comments

– Java supports three types of comment delimiters – The /* and */ - enclose text that is to be treated as a comment by the compiler – // - indicate that the rest of the line is to be treated as a comment by the Java compiler – the /** and */ - the text is also part of the automatic class documentation that can be generated using JavaDoc.

5

slide-6
SLIDE 6

Java Program Structure

  • Five types of Tokens in Java:

– Reserved keywords – Identifiers – Literals – Operators – Separators

6

slide-7
SLIDE 7

Reserved keywords

  • Words with special meaning to the compiler
  • The following keywords are reserved in the Java language. They can

never be used as identifiers:

  • Some are not used but are reserved for further use. (Eg.: const, goto)

abstract assert boolean break byte case catch char class const continue default do double else extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void violate while

7

slide-8
SLIDE 8

Identifiers

  • Programmer given names
  • Identify classes, methods, variables, objects, packages.
  • Identifier Rules:

– Must begin with

  • Letters , Underscore characters ( _ ) or Any currency symbol

– Remaining characters

  • Letters
  • Digits

– As long as you like!! (until you are tired of typing) – The first letter can not be a digit – Java is case sensitive language

8

slide-9
SLIDE 9

Identifiers

  • Identifiers‘ naming conventions

– Class names: starts with cap letter and should be inter-cap e.g. StudentGrade – Variable names: start with lower case and should be inter- cap e.g. varTable – Method names: start with lower case and should be inter- cap e.g. calTotal – Constants: often written in all capital and use underscore if you are using more than one word.

9

slide-10
SLIDE 10

Literals

  • Explicit (constant) value that is used by a program
  • Literals can be digits, letters or others that represent

constant value to be stored in variables – Assigned to variables – Used in expressions – Passed to methods

  • E.g.

– Pi = 3.14; // Assigned to variables – C= a * 60; // Used in expressions – Math.sqrt(9.0); // Passed to methods

10

slide-11
SLIDE 11

Operator

  • symbols that take one or more arguments

(operands) and operates on them to produce a result

  • 5 Operators

– Arithmetic operators – Assignment operator – Increment/Decrement operators – Relational operators – Logical operators

11

slide-12
SLIDE 12

Separators

  • Indicate where groups of codes are divided and arranged

Name Symbol

Parenthesis () braces {} brackets [] semicolon ; comma , , period

. 12

slide-13
SLIDE 13

Object Oriented Programming

  • Objects and Classes
  • Encapsulation
  • Inheritance
  • Polymorphism

13

slide-14
SLIDE 14

Classes and Objects

  • The underlying structure of all Java programs is classes.
  • Anything we wish to represent in Java must be encapsulated

in a class – defines the ―state‖ and ―behavior‖ of the basic program components known as objects.

  • Classes create objects
  • A class essentially serves as a template for an object and

behaves like a basic data type ―int‖.

14

slide-15
SLIDE 15

15

Classes and Objects

  • A class

is a collection

  • f

fields (data) and methods (procedure or function) that operate on that data.

  • The basic syntax for a class definition:

class ClassName { [fields declaration] [methods declaration] }

slide-16
SLIDE 16

Classes and Objects

public class Rectangle{ // my rectangle class }

16

Rectangle Length Width Perimeter() area()

slide-17
SLIDE 17

17

Adding Fields

  • The fields and methods are called class members
  • Add fields:
  • The fields (data) are also called the instance variables.

public classRectangle { public double length; public double width; }

slide-18
SLIDE 18

18

Adding Methods

  • A class with only data fields has no life. Objects created by

such a class cannot respond to any messages.

  • Methods are declared inside the body of the class but

immediately after the declaration of data fields.

  • The general form of a method declaration is:

type MethodName (parameter-list) { Method-body; }

slide-19
SLIDE 19

19

Adding Methods

public class Rectangle { public double length public double width; // //Methods to return perimeter and area public double perimeter() { return 2 *(length+width); } public double area() { return length * width; } }

Method Body

slide-20
SLIDE 20

20

Creating an Object

  • An object is an instance of a class
  • Uniquely identified by

– its name – defined state,

  • represented by the values of its attributes in a particular

time

slide-21
SLIDE 21

Creating an Object

  • Creating an object is a two step process

– Creating a reference variable

Syntax: <class idn><ref. idn>;

  • eg. Rectangle r1;

– Setting or assigning the reference with the newly created object. – Syntax: <ref. idn> = new <class idn>(…); r1 = new Rectangle(); – The two steps can be done in a single statement Rectangle r1 = new Rectangle();

21

slide-22
SLIDE 22

22

Creating an Object

  • Example

– Rectangle aRec,bRec;

  • aRec, bRec simply refers to a Rectangle object, not an object

itself.

aRec

null

bRec

null

slide-23
SLIDE 23

Creating an Object

  • Objects are created dynamically using the

new keyword.

  • aRec and bRec refer to Rectangle objects

23

bRec= new Rectangle() ; aRec= new Rectangle();

slide-24
SLIDE 24

24

Creating an Object

aCircle = new Circle(); bCircle = new Circle() ; bCircle = aCircle; aCircle bCircle Before Assignment aCircle bCircle After Assignment

slide-25
SLIDE 25

25

Accessing Object Data

  • We use dot (“.”) operator

Rectangle aRec= new Rectangle(); aRec.length = 2.0 // initialize length aRec.width = 2.0 //initialize width

ObjectName.VariableName ObjectName.MethodName(parameter-list)

slide-26
SLIDE 26

26

Executing Methods in Object/Circle

  • Using Object Methods:

Rectangle aRec= new Rectangle(); double area; aCircle.r= 1.0; area = aRec.area(); sent ‘message’ to aRec

slide-27
SLIDE 27

27

Using Rectangle Class

//Add Rectangle class code here class MyMain { public static void main(String args[]) { Rectangle aRec; // creating reference aRec= new Rectangle(); aRec.length = 2.0 // initialize length aRec.width = 2.0 //initialize width double area = aRec.area(); // invoking method double per = aRec.perimeter(); System.out.println(“Area is “+area); System.out.println(“Perimeter is “+ per); } }

slide-28
SLIDE 28

28

What is encapsulation?

  • Hiding the data within the class
  • Making it available only through the

methods

  • Each object protects and manages its
  • wn data. This is called self-governing.

Methods Data

slide-29
SLIDE 29

29

Why encapsulation?

  • To hide the internal implementation details
  • f your class so they can be easily changed
  • To protect your class against accidental or

willful mistakes

  • In general

– Encapsulation separates the implementation details from the interface

slide-30
SLIDE 30

30

Visibility Modifiers

  • In Java we accomplish encapsulation using

visibility modifiers.

– Public

  • least restrictive
  • Can be directly referenced from outside of an object.
  • visible to any class in the Java program

– Private

  • most restrictive
  • Can’t

be accessed by anywhere

  • utside

the enclosing class

  • Cannot be referenced externally.
  • Instance data should be defined private.

– Package - default

  • Intermediate b/n private and public
  • access only to classes in the same package

– Protected

  • access to classes in the same package and to all subclasses
slide-31
SLIDE 31

31

Using Set and Get Methods

  • A class‘s private fields can manipulate only by

methods of that class

  • How can we access those data outside?

– Using set and get methods

  • Set methods

– public method that sets private variables – Does not violate notion of private data

  • Change only the variables you want

– Called mutator methods (change value)

  • Get methods

– public method that displays private variables – Again, does not violate notion of private data

  • Only display information you want to display

– Called accessor or query methods

slide-32
SLIDE 32

32

Inheritance

  • Inheritance allows a software developer to derive a new

class from an existing one

  • For the purpose of

– reuse – enhancement, – adaptation, etc

  • The existing class is called the parent class or superclass
  • The derived class is called the child class or subclass.
  • Classes often have a lot of state and behavior in common

– Result: lots of duplicate code!

  • Super classes are more generic and sub classes are

specific version of the super classes

slide-33
SLIDE 33

33

Inheritance

  • Two ways of expressing class relationships

– Generalization/Specialization

  • ‗is a‖ relationship
  • Circle is a shape

– Whole-part

  • Part of or ―has a‖ relationship
  • Employee class has a BirthDate class
  • Called aggregation
  • Inheritance creates an is-a relationship
slide-34
SLIDE 34

34

Inheritance

  • The child class inherits the methods and data

defined for the parent class

  • To tailor a derived class, the programmer can

add new variables or methods, or can modify the inherited ones

  • Software reuse is at the heart of inheritance
  • By using existing software components to

create new ones, we capitalize on all the effort that went into the design, implementation, and testing of the existing software

slide-35
SLIDE 35

35

Deriving Subclasses

  • In Java, we use the reserved word extends to

establish an inheritance relationship

  • Syntax

class subClassName extends superClassName

{ // body of class } e.g.

class 2D_Shape extends Shape { // class contents }

slide-36
SLIDE 36

36

Some Inheritance Details

  • An instance of a child class does not

rely on an instance of a parent class

– Hence we could create a Circle object without having to create a Shape object first

  • Inheritance is a one-way street

– The Shape class cannot use variables or methods declared explicitly in the Triangle class

slide-37
SLIDE 37

37

Multiple Inheritance

  • Java supports single inheritance, meaning that a derived

class can have only one parent class

  • Multiple inheritance allows a class to be derived from two
  • r more classes, inheriting the members of all parents
  • Collisions, such as the same variable name in two

parents, have to be resolved

  • In most cases, the use of interfaces gives us aspects of

multiple inheritance without the overhead (will discuss later)

slide-38
SLIDE 38

38

Interfaces

  • Interface is a conceptual entity similar to a class.
  • But :

– Can contain only constants (final variables) and abstract method (no implementation) - Different from classes.

  • Use when a number of classes share a common

interface.

  • Each class should implement the interface.
slide-39
SLIDE 39

39

Interfaces

  • An interface is basically a kind of class—it contains

methods and variables, but they have to be only abstract methods and final fields/variables.

  • Therefore,

it is the responsibility

  • f

the class that implements an interface to supply the code for methods.

  • A class can implement any number of interfaces, but

cannot extend more than one class at a time.

  • Therefore, interfaces are considered as an informal way of

realizing multiple inheritance in Java.

slide-40
SLIDE 40

40

Interfaces Definition

  • Syntax (appears like abstract class):
  • Example:

interface InterfaceName { // Constant/Final Variable Declaration // Methods Declaration – only method body } interface Shape { public double area( ); }

slide-41
SLIDE 41

41

Implementing Interfaces

  • Interfaces are used like super-classes who

properties are inherited by classes. This is achieved by creating a class that implements the given interface as follows:

class ClassName implements InterfaceName [, InterfaceName2, …] { // Body of Class }

slide-42
SLIDE 42

42

Interfaces and Software Engineering

  • Interfaces provide templates of behaviour that other

classes are expected to implement.

  • Separates out a design hierarchy from implementation

hierarchy. This allows software designers to enforce/pass common/standard syntax for programmers implementing different classes.

  • Pass method descriptions, not implementation
  • Classes implement interfaces.
slide-43
SLIDE 43

Polymorphism

  • The term polymorphism literally means "having many

forms‖

  • Polymorphism is an object-oriented concept that allows us

to create versatile software designs

  • In OOP, polymorphism promotes code reuse by calling the

method in a generic way.

  • For example we can calculate the area

by calling the area() method on all shape objects. But depending on the type of shape(whether Circle or Rectangle) the correct version of area() will be called.

43

slide-44
SLIDE 44

Binding

  • Consider the following method invocation:
  • bj.doIt();
  • At some point, this invocation is bound to the definition of the

method that it invokes

  • If this binding occurred at compile time, then that line of code

would call the same method every time

  • However, Java defers method binding until run time -- this is

called dynamic binding or late binding

44

slide-45
SLIDE 45

Polymorphism

  • Suppose we create the following reference variable:

Shape myShapes;

  • Java allows this reference to point to an Shape object,
  • r to any object of any compatible type
  • This compatibility can be established using inheritance
  • r using interfaces
  • Careful use of polymorphic references can lead to

elegant, robust software designs

45

slide-46
SLIDE 46

46