Presentation is loading. Please wait.

Presentation is loading. Please wait.

Enhancing classes Visibility modifiers and encapsulation revisited

Similar presentations


Presentation on theme: "Enhancing classes Visibility modifiers and encapsulation revisited"— Presentation transcript:

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

2 Passing 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

3 Example: 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);

4 Overloading 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

5 Overloading Methods float tryMe (int x) { return x + .375; } Version 1
float tryMe (int x, float y) { return x*y; } Version 2 result = tryMe (25, 4.32) Invocation

6 Overloaded Methods The println method is overloaded: etc.
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);

7 Constructor 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

8 // ------------------------------------------------
// 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. hours: the hours to be set (0-23) minutes: the minutes to be set (0-59) 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;

9 Overloading 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?

10 Visibility 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

11 Any other class can use MyClass public MyClass { // … }

12 The 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

13 Example - a Math 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) {

14 Use 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

15 Static 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)

16 Static 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;

17 Static Methods and Instance Variables
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

18 Static 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

19 Nested 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 Nested Class

20 Nested 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

21 Nested 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.class Outside$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

22 Example: a nested class
// regular class definition public 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"); }

23 Writing 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

24 Division 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); }

25 Division 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); } // Returns true iff number is prime public static boolean isPrime(int number) { // determines if number is prime


Download ppt "Enhancing classes Visibility modifiers and encapsulation revisited"

Similar presentations


Ads by Google