33
Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested C LASSES AND METHODS Muhammad Adil Raja Roaming Researchers, Inc. cbnd April 14, 2015

Classes And Methods

Embed Size (px)

Citation preview

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

CLASSES AND METHODS

Muhammad Adil Raja

Roaming Researchers, Inc.

cbnd

April 14, 2015

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

OUTLINE I

1 INTRODUCTION

2 ENCAPSULATION AND INSTANTIATION

3 CLASS DEFINITIONS

4 METHODS

5 INTERFACES IN JAVA

6 PROPERTIES

7 INNER OR NESTED CLASSES

8 CLASS DATA FIELDS

9 SUMMARY

10 REFERENCES

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

INTRODUCTION I

Chapters 4 and 5 discuss two sides of OOP.

Chapter 4 discusses the static, compile timerepresentation of object-oriented programs.

Chapter 5 discusses the dynamic, run time behavior

Both are important, and both chapters should be understoodbefore you begin further investigation of object-orientedprogramming.

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

SAME IDEAS DIFFERENT TERMS I

All OOP languages have the following concepts, although theterms they use may differ:

CLASSES: object type, factory object.

INSTANCES: objects

MESSAGE PASSING: method lookup, member functioninvocation, method binding.

METHODS: member function, method function

INHERITANCE: subclassing

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

ENCAPSULATION AND INSTANTIATION I

ENCAPSULATION

The purposeful hiding of information, thereby reducing theamount of details that need to be remembered/communicatedamong programmers.

A SERVICE VIEW

The ability to characterise an object by the service it provides,without knowing how it performs its task.

INSTANTIATION

The ability to create multiple instances of an abstraction.

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

INTERNAL AND EXTERNAL VIEWS I

TWO VIEWS OF SOFTWARE

Encapsulation means there are two views of the same system.The outside, or service view, describes what an object does.The inside, or implementation view, describes how it does it.

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

BEHAVIOR AND STATE I

A class can also be viewed as a combination of behavior andstate.

BEHAVIOR: The actions that an instance can perform inresponse to a request. Implemented by methods.

STATE: The data that an object must maintain in order tosuccessfully complete its behavior. Stored ininstance variables (also known as data members,or data fields).

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

CLASS DEFINITIONS I

We will use as a running example the class definition for aplaying card abstraction, and show how this appears inseveral languages.

Languages include Java, C++, C#, Delphi Pascal, ApplePascal, Ruby, Python, Eiffel, Objective-C and Smalltalk.

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

CLASS DEFINITIONS II

A TYPICAL EXAMPLE, CLASS DEFINITION IN C++

class PlayingCard {public :

enum Su i t s { Spade , Diamond , Club , Heart } ;

Su i t s s u i t ( ) { return su i tVa lue ; }i n t rank ( ) { return rankValue ; }

private :Su i t s su i tVa lue ;i n t rankValue ;

} ;

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

CLASS DEFINITIONS III

Note syntax for methods, data fields, and visibility modifiers.(Will see more on syntax later).

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

VISIBILITY MODIFIERS I

The terms public and private are used to differentiate theinternal and external aspects of a class.

Public features can be seen and manipulated by anybody –they are the external (interface or service) view.

Private features can be manipuated only within a class.

They are the internal (implementation) view.

Typically methods are public and data fields are private, buteither can be placed in either category.

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

VISIBILITY MODIFIERS II

A C-SHARP CLASS DEFINITION

enum Su i t s { Spade , Diamond , Club , Heart } ;

class PlayingCard {public Su i t s s u i t ( ) { return su i tVa lue ; }public i n t rank ( ) { return rankValue ; }

private Su i t s su i tVa lue ;private i n t rankValue ;

}

C# class definitions have minor differences, no semicolon atend, enum cannot be nested inside class, and visibilitymodifiers are applied to methods and data fields individually.

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

VISIBILITY MODIFIERS III

JAVA CLASS DEFINITION

class PlayingCard {public i n t s u i t ( ) { return su i tVa lue ; }public i n t rank ( ) { return rankValue ; }

private i n t su i tVa lue ;private i n t rankValue ;

public s t a t i c f i n a l i n t Spade = 1;public s t a t i c f i n a l i n t Diamond = 2;public s t a t i c f i n a l i n t Club = 3;public s t a t i c f i n a l i n t Heart = 4 ;

}

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

VISIBILITY MODIFIERS IV

Java also applies visibility modifiers to each item indivually.Does not have enumerated data types, uses symbolicconstants instead.

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

STATIC AND FINAL I

Notice how symbolic constants are defined in Java:static means that all instance share the same value. Oneper class. Similar meaning in many languages.final is Java specific, and means it will not be reassigned.(C++ has const keyword that is similar, although notexactly the same).

STATIC AND FINAL

public s t a t i c f i n a l i n t Spade = 1;public s t a t i c f i n a l i n t Diamond = 2;public s t a t i c f i n a l i n t Club = 3;public s t a t i c f i n a l i n t Heart = 4 ;

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

METHODS I

Although syntax will differ depending upon language, allmethods have the following:

A name that will be matched to a message to determinewhen the method should be executed.

A signature, which is the combination of return type andargument types. Methods with the same name can bedistinguished by different signatures.

A body, which is the code that will be executed when themethod is invoked in response to a message.

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

METHODS II

AN EXAMPLE FROM C-SHARP

class PlayingCard {/ / cons t ruc to r , i n i t i a l i z e new p lay ing card

public PlayingCard ( Su i t s is , i n t i r ){ s u i t = i s ; rank = i r ; faceUp = true ; }

/ / opera t ions on a p lay ing cardpublic boolean isFaceUp ( ) { return faceUp ; }public i n t rank ( ) { return rankValue ; }public Su i t s s u i t ( ) { return su i tVa lue ; }public void setFaceUp ( boolean up ) { faceUp = up ; }public void f l i p ( ) { setFaceUp ( ! faceUp ) ; }public Color co l o r ( ) {

i f ( ( s u i t ( ) == Su i t s . Diamond ) | | ( s u i t ( ) == Su i t s . Heart ) )return Color . Red ;

return Color . Black ;}

/ / p r i v a t e data valuesprivate Su i t s su i tVa lue ;private i n t rankValue ;private boolean faceUp ;

}

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

METHODS III

CONSTRUCTOR

class PlayingCard {/ / cons t ruc to r , i n i t i a l i z e new p lay ing card

public PlayingCard ( Su i t s is , i n t i r ){ s u i t = i s ; rank = i r ; faceUp = true ; }

. . .

}

A constructor is a method that is used to initialize a newlyconstructed object.

In C++, Java, C# and many other languages.

It has the same name as the class.

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

METHODS IV

ACCESSOR (OR GETTER) METHODS

class PlayingCard {. . .

/ / opera t ions on a p lay ing cardpublic i n t rank ( ) { return rankValue ; }public Su i t s s u i t ( ) { return su i tVa lue ; }. . .private i n t rankValue ;

}

An accessor (or getter) is a method that simply returns aninternal data value:

Why Use an Accessor? There are many reasons why anaccessor is preferable to providing direct access to a datafield.You can make the data field read-only.

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

METHODS V

It provides better documentation that the data field isaccessibleIt makes it easier to later change the access behavior(count number of accesses, whatever).Some conventions encourage the use of a name thatbegins with get, (as in getRank()), but this is not universallyfollowed.

SETTERS (OR MUTATORS)

class PlayingCard {

/ / opera t ions on a p lay ing cardpublic void setFaceUp ( boolean up ) { faceUp = up ; }

. . ./ / p r i v a t e data values

private boolean faceUp ;}

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

METHODS VI

A setter (sometimes called a mutator method) is a methodthat is used to change the state of an object.

Mutators are less common than accessors, but reasons forusing are similar.

Constant data fields.

Some languages allow data fields to be declared asconstant (const modifier in C++, final in Java, otherlanguages have other conventions).

Constant data fields can be declared as public, since theycannot be changed.

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

ORDER OF METHODS I

For the most part, languages don’t care about the orderthat methods are declared.Here are some guidelines:List important topics first.Constructors are generally very important, list them first.Put public features before private ones.Break long lists into groupsList items in alphabetical order to make it easier to search.Remember that class definitions will often be read bypeople other than the original programmer.Remember the reader, and make it easy for them.

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

SEPARATION OF DEFINITION AND IMPLEMENTATION I

In some languages (such as C++ or Object Pascal) thedefinition of a method can be separated from itsimplementation.They may even be in a different file:

SEPARATION OF DEFINITION AND IMPLEMENTATION

class PlayingCard {public :

. . .Colors co l o r ( ) ;. . .

} ;

PlayingCard : : Colors PlayingCard : : co l o r ( ){

/ / r e t u r n the face c o l o r o f a p lay ing cardi f ( ( s u i t == Diamond ) | | ( s u i t == Heart ) )

return Red ;return Black ;

}

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

SEPARATION OF DEFINITION AND IMPLEMENTATION II

Notice the need for fully-qualified names.

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

CONSIDERATIONS IN METHOD DEFINITIONS I

In C++ you have a choice to define a method in the classinterface, or separately in an implementation file. How doyou decide?

Readability.

Only put very small methods in the class definition, so thatit is easier to read.

Semantics. Methods defined in class interface may (at thedescretion of the compiler) be expanded in-line.

Another reason for only defining very small methods thisway.

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

PREPARING FOR CHANGE I

An interface is like a class, but it provides noimplementation.Later, another class can declare that it supports theinterface, and it must then give an implementation.

AN INTERFACE IN JAVA

public inter face Sto r ing {void wr i teOut ( Stream s ) ;void readFrom ( Stream s ) ;

} ;

public class BitImage implements Sto r ing {void wr i teOut ( Stream s ) {

/ / . . .}void readFrom ( Stream s ) {

/ / . . .}

} ;

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

PREPARING FOR CHANGE II

We will have much more to say about interfaces later after wediscuss inheritance.

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

PROPERTIES I

Properties are a way to define getters and setters, butallow them to be used as if they were simple assignmentsand expressions:

PROPERTIES

w r i t e l n ( ’ rank i s ’ , aCard . rank ) ; (∗ rank i s p roper ty o f card ∗)aCard . rank = 5; (∗ changing the rank proper ty ∗)

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

PROPERTIES II

PROPERTIES IN C-SHARP

public class PlayingCard {public i n t rank {

get{

return rankValue ;}se t{

rankValue = value ;}

}. . .private i n t rankValue ;

}

Omitting a set makes it read-only, omitting a get makes itwrite-only.

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

SOFTWARE COMPONENTS I

Some languages (C++ or Java) allow a class definition tobe given inside another class definition.Whether the inner class can access features of the outerclass is different in different languages.

INNER CLASSES IN JAVA

class L inkedL i s t {

. . .private class Link { / / i nne r c lass

public i n t value ;public Link next ;

}}

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

CLASSE DATA FIELDS I

Idea is that all instances of a class can share a commondata field. Simple idea, but how to resolve the followingparadox. All instances have the same behavior:

Either they all initialize the common area, which seemsbad, or

Nobody initializes the common area, which is also bad.

Different languages use a variety of mechanisms to getaround this. See text for details.

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

SUMMARY I

In this chapter we have examined the static, or compiletime features of classes:The syntax used for class definition.The meaning of visibility modifiers (public and private).The syntax used for method definition.Accessor or getter methods, and mutator or settermethods.Variations on class themes.Interfaces.Properties.Nested classes.Class data fields.

Introduction Encapsulation and Instantiation Class Definitions Methods Interfaces in Java Properties Inner or Nested Classes Class Data Fields Summary References

REFERENCES I

Images and content for developing these slides have beentaken from the follwoing book.

An Introduction to Object Oriented Programming, TimothyBudd.This presentation is developed using Beamer:

Frankfurt, spruce.