overview of oop in java - southern illinois university...

46
Overview of OOP in Java 1 Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale [email protected] Room - 3131

Upload: others

Post on 21-May-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Overview of OOP in Java

1

Tessema M. MengistuDepartment of Computer Science

Southern Illinois University [email protected]

Room - 3131

Outline

• Java Basics

• Classes and Objects

• Encapsulation

• Inheritance

• Polymorphism

2

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

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

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

Java Program Structure

• Five types of Tokens in Java:

– Reserved keywords

– Identifiers

– Literals

– Operators

– Separators

6

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

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 language8

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

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

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

Separators

• Indicate where groups of codes are divided and arranged

Name Symbol

Parenthesis ()

braces {}

brackets []

semicolon ;

comma , ,

period .

12

Object Oriented Programming

• Objects and Classes

• Encapsulation

• Inheritance

• Polymorphism

13

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

15

Classes and Objects• A class is a collection of 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]

}

Classes and Objects

public class Rectangle{

// my rectangle class

}

16

Rectangle

LengthWidth

Perimeter()area()

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;

}

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;}

19

Adding Methodspublic 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

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

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

22

Creating an Object• Example

– Rectangle aRec,bRec;

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

itself.

aRec

null

bRec

null

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();

24

Creating an Object

aCircle = new Circle();bCircle = new Circle() ;

bCircle = aCircle;

aCircle bCircle

Before Assignment

aCircle bCircle

After Assignment

25

Accessing Object Data• We use dot (“.”) operator

Rectangle aRec= new Rectangle();

aRec.length= 2.0 // initialize lengthaRec.width= 2.0 //initialize width

ObjectName.VariableName

ObjectName.MethodName(parameter-list)

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

27

Using Rectangle Class//Add Rectangle class code hereclass 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 widthdouble area = aRec.area(); // invoking methoddouble per = aRec.perimeter();System.out.println(“Area is “+area);System.out.println(“Perimeter is “+ per);

}}

28

What is encapsulation?

• Hiding the data within the class

• Making it available only through the

methods

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

Methods

Data

29

Why encapsulation?

• To hide the internal implementation detailsof your class so they can be easily changed

• To protect your class against accidental orwillful mistakes

• In general

– Encapsulation separates the implementationdetails from the interface

30

Visibility Modifiers

• In Java we accomplish encapsulation usingvisibility 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 outside 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

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

32

Inheritance

• Inheritance allows a software developer to derive a newclass 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 arespecific version of the super classes

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

34

Inheritance

• The child class inherits the methods and datadefined for the parent class

• To tailor a derived class, the programmer canadd new variables or methods, or can modifythe inherited ones

• Software reuse is at the heart of inheritance

• By using existing software components tocreate new ones, we capitalize on all theeffort that went into the design,implementation, and testing of the existingsoftware

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

}

36

Some Inheritance Details

• An instance of a child class does notrely on an instance of a parent class

– Hence we could create a Circle objectwithout having to create a Shape objectfirst

• Inheritance is a one-way street

– The Shape class cannot use variables ormethods declared explicitly in the Triangleclass

37

Multiple Inheritance

• Java supports single inheritance, meaning that a derivedclass can have only one parent class

• Multiple inheritance allows a class to be derived from twoor more classes, inheriting the members of all parents

• Collisions, such as the same variable name in twoparents, have to be resolved

• In most cases, the use of interfaces gives us aspects ofmultiple inheritance without the overhead (will discusslater)

38

Interfaces

• Interface is a conceptual entity similar to a class.

• But :

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

• Use when a number of classes share a common interface.

• Each class should implement the interface.

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 of 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.

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( );

}

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}

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.

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

Binding

• Consider the following method invocation:

obj.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

Polymorphism

• Suppose we create the following reference variable:

Shape myShapes;

• Java allows this reference to point to an Shape object,

or to any object of any compatible type

• This compatibility can be established using inheritance

or using interfaces

• Careful use of polymorphic references can lead to

elegant, robust software designs

45

46