unit 6 1 enhancing classes h visibility modifiers and encapsulation revisited h static methods and...

25
1 unit 6 Enhancing classes Enhancing classes Visibility modifiers and encapsulation revisited Static methods and variables Method/constructor overloading Nested classes basic programmin g concepts object oriented programmin g topics in computer science syllabus

Post on 20-Dec-2015

216 views

Category:

Documents


0 download

TRANSCRIPT

1unit 6

Enhancing classesEnhancing classes

Visibility modifiers and encapsulation revisited

Static methods and variables Method/constructor overloading Nested classes

basic programming

concepts

object oriented programming

topics in computer science

syllabus

2unit 6

Passing Objects to MethodsPassing Objects to Methods

Parameters in a Java method are passed by value: a copy of the actual parameter (the value passed in) is stored into the formal parameter (in the method header)

Passing parameters is essentially an assignment

Both primitive types and object references can be passed as parameters

When an object is passed to a method, the actual parameter and the formal parameter become aliases

3unit 6

Example: Arrays as parametersExample: Arrays as parameters

static void setArrayEl(int[] arr, int i, int n){

arr[i] = n; }

static void setEl(int el, int newVal){ el = newval; }

public static void main(String[] args){ int[] samples = {1,2,3,4,5,6}; setArrayEl(samples,1,0); setEl(samples[1],10); }

4unit 6

Overloading MethodsOverloading Methods

Method overloading is the process of using the same method name for multiple methods

The signature of each overloaded method must be unique The signature includes the number, type, and order of the

parameters; overloaded methods differ by the number and/or type of parameters they get.

The compiler must be able to determine which version of the method is being invoked by analyzing the parameters

The return type of the method is not part of the signature

5unit 6

Overloading MethodsOverloading Methods

float tryMe (int x){

return x + .375;}

Version 1Version 1

float tryMe (int x, float y){

return x*y;}

Version 2Version 2

result = tryMe (25, 4.32)

InvocationInvocation

6unit 6

Overloaded MethodsOverloaded Methods

The println method is overloaded: println (String s)

println (int i)

println (double d)

etc.

The following lines invoke different versions of the println method:

System.out.println ("The total is:");

System.out.println (total);

7unit 6

Constructor OverloadingConstructor Overloading

Constructors can be overloaded:• An overloaded constructor provides multiple ways to set

up a new object

• The overloaded constructors differ by the number and type of parameters they get.

When we construct an object, the compiler decides which constructor to invoke according to the type of the actual parameters

A constructor with no parameters is called a default constructor

8unit 6

// ------------------------------------------------// Constructs a new clock with the specified hours,// minutes and seconds read. // If one of the paramenters is not in the allowed// range, the time will be reset to 00:00:00.// @param hours: the hours to be set (0-23)// @param minutes: the minutes to be set (0-59)// @param seconds: the seconds to be set (0-59)// ------------------------------------------------

public Clock(int hours, int minutes, int seconds) { if ((seconds >= 0) && (seconds < 60) && (minutes >= 0) && (minutes < 60) && (hours >= 0) && (hours < 24)) { this.hours = hours; this.minutes = minutes; this.seconds = seconds; } else { this.hours = 0; this.minutes = 0; this.seconds = 0; }}

9unit 6

Overloading ConstructorsOverloading Constructors

Clock c1 = new Clock();

// default constructor

Clock c2 = new Clock(23,12,50);

// Clock(int, int, int) constructor

The constructor must always check the parameters: an object should not be initialized to an inconsistent state

What is an inconsistent state in a clock?

10unit 6

Visibility Modifiers - ClassesVisibility Modifiers - Classes

A class can be defined either with the public modifier or without a visibility modifier

If a class is declared as public it can be used by any other class

If a class is declared without a visibility modifier it has a default visibility; this draws a limit to which other classes can use this class

Classes that define a new type of objects, that are supposed to be used anywhere, should be declared public

11unit 6

public MyClass {

// …

}

Any other class can use

MyClass

12unit 6

The Static Modifier, Container ClassThe Static Modifier, Container Class

The static modifier can be applied to variables or methods

It associates a variable or method with the class rather than an object

Methods that are declared as static do not act upon any particular object; they just encapsulate a given task, a given algorithm

Container class: we can write a class that is a collection of static methods; such a class is not meant to define a new type of object, it is just used as a library for utilities that are related in some way

13unit 6

Example - a Example - a MathMath Class Class

// ---------------------------------// A library of mathematical methods// ---------------------------------public class Math { // ------------------------------------------- // Computes the trigonometric sine of an angle // ------------------------------------------- public static double sin(double x) { // ... } // ---------------------------------------- // Computes the logarithm of a given number // ---------------------------------------- public static double log(double x) { // ... } // ...}

14unit 6

Use of Static MethodsUse of Static Methods

When we call a static method we should specify the class to which method belongs.double x = Math.sin(alpha);int c = Math.max(a,b);double y = Math.random();

The main method is static; it is invoked by the system without creating an object

If a static method calls another static method of the same class we can omit the class-name prefix

15unit 6

Static VariablesStatic Variables

A variable that is declared static is associated with the class itself and not with an instance of it

Static variables are also called class variables

We use static variables to store information that is not associated with a given object, but is relevant to the class

We have already seen such usage - constants of a class (final static)

16unit 6

Static Variables - ExampleStatic Variables - Example

public class BankAccount { private long accountNumber; // serial number private float balance; // balance in dollars private static int numberOfAccounts = 0;

public BankAccount() { this.accountNumber = numberOfAccounts; numberOfAccounts++; this.balance = 0;

this.owner = “Smith”; }

public static int getNumberOfAccounts { return numberOfAccounts; }}

17unit 6

Static Methods and Instance VariablesStatic Methods and Instance Variables

Static methods:• cannot reference instance variables (i.e.,

access instance variable when an object doesn’t exist)

• can reference static variables or local variables (within the method)

• this has no meaning inside a static method, thus its use inside a static method is not allowed

Instance methods can access both instance and static variables

18unit 6

Static VariablesStatic Variables

Normally, each object has its own data space If a variable is declared as static, only one copy of

the variable exists

private static float price; Memory space for a static variable is created as

soon as the class in which it is declared is loaded All objects created from the class share access to

the static variable Changing the value of a static variable in one

object changes it for all others

19unit 6

Nested ClassesNested Classes

In addition to a class containing data and methods, it can also contain other classes

A class declared within another class is called a nested class

Outer Class

NestedClass

20unit 6

Nested ClassesNested Classes

A nested class has access to the variables and methods of the outer class, even if they are declared private

In certain situations this makes the implementation of the classes easier because they can easily share information

Furthermore, the nested class can be protected by the outer class from external use

21unit 6

Nested ClassesNested Classes

A nested class produces a separate bytecode file

If a nested class called Inside is declared in an outer class called Outside, two bytecode files will be produced:

Outside.classOutside$Inside.class

Nested classes can be declared as static, in which case they cannot refer to instance variables or methods

A nonstatic nested class is called an inner class

22unit 6

Example: a nested classExample: a nested class

// regular class definitionpublic class Farm { private String country;

// inner class definition private class Dog {

public void makeSound() { if (country.equals("Israel")) System.out.println("how-how"); else System.out.println("woof-woof"); } }}

23unit 6

Writing code: division into methodsWriting code: division into methods

Complicated tasks or tasks that occur often within a class should be wrapped in a method

This results in a readable and manageable code

This is very helpful when implementing algorithms, or when we need “helper” methods in classes

24unit 6

Division into Methods - ExampleDivision into Methods - Example

// Prints all the prime numbers

public class Primes {

public static void main(String[] args) { int number = 0; while (true) { number = number + 1; if (isPrime(number)) System.out.println(number); } }}

25unit 6

Division into Methods - ExampleDivision into Methods - Example // Prints all the prime numberspublic class Primes {

public static void main(String[] args) { int number = 0; while (true) { number = number + 1; if (isPrime(number)) System.out.println(number); } } // Returns true iff number is prime public static boolean isPrime(int number) { // determines if number is prime }

}