html5-img
1 / 49

Defining New Classes

Defining New Classes. In this lecture: Defining classes Instance variables Constructors Defining methods and passing parameters Visibility modifiers Static methods and variables Method overloading Documentation comments. Defining New Classes.

maebanks
Télécharger la présentation

Defining New Classes

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Defining New Classes • In this lecture: • Defining classes • Instance variables • Constructors • Defining methods and passing parameters • Visibility modifiers • Static methods and variables • Method overloading • Documentation comments

  2. Defining New Classes • Generally, classes can be used for two purposes. • Container classes: • As containers of static methods: methods that carry out a given tasks that are not bound to any particular object (e.g., the main() method). • These static methods usually have something in common (e.g., the Math class) • Definition classes: • These classes define new objects, in a way that we will soon see.

  3. Defining New Classes • The class Rectangles is an example of the first kind. It is a container for the method main which draws four rectangles. • The class Turtle is an example of the second kind. It defines a new type of objects, Turtle objects. • We will now focus on the second kind.

  4. A Clock Class /** * A clock representation class */ public class Clock { // The hours, minutes, and second read private int hours, minutes, seconds; // ... }

  5. Instance Variables • Recall that a class must define the state of an object and its behaviour. • We declare state variables (variables that hold the state of the object) in a similar way to that of regular variables only they appear outside methods. • State variables are also called instance variables or fields. • Rougly speaking, the private modifier means that the variables are not part of the object’s interface.

  6. Constructors • Objects must be initialized before they can be used. • We must specify what is the initial state of the object before we can use it. • This is very similar to primitive data types: when we declare a new variable of type int, for example, we must give it an initial value. • We specify the way an object is initialized using a constructor, which is a special method which is invoked every time we create a new object

  7. Constructors /** * A clock representation class */ public class Clock { // The hours, minutes, and second read private int hours, minutes, seconds; /** * Constructs a new clock. Resets the clock * to the time 00:00:00 */ public Clock() { hours = 0; minutes = 0; seconds = 0; } }

  8. Constructors • The statement new Clock()does the following: • 1) Allocates the memory for a new clock object • 2) Initializes its state by calling the constructor clock hours minutes seconds clock hours 0 minutes 0 seconds 0

  9. Methods • To make the date object useful, we must provide methods that define its behaviour. • We declare methods in a similar way to the way the method main was declared: public static void main(String[] args) { // ... } • Only there’s a big difference: • the main method was static, which means it wasn’t bound to a specific object • we want to declare instance methods, which are bound to a specific object

  10. public class Clock { /* ... */ private int hours, minutes, seconds; /** ... */ public Clock() { // ... } /** * Advances the clock by one hour. */ public void hourElapsed() { hours = (hours + 1) % 24; } }

  11. Methods • The modifier public denotes that the method hourElapsed() is part of the interface of the class ( it is one of the services the class exposes to outside world clients) • The exact meaning of the keyword public will be discussed later • The keyword void denotes that the method hourElapsed() has no return value.

  12. public class Clock { // ... instance variables and constructor /** * Advances the clock by one hour. */ public void hourElapsed() { hours = (hours + 1) % 24; } /** * Returns the hour read. */ public int getHours() { return hours; } }

  13. Return Types • The return type of a method indicates the type of value that the method sends back to the calling client • The return-type of getHours() is int. When a client ask for the hours read of a clock it gets the answer as an int value. • A method that does not return a value (such ashourElapsed()) has avoidreturn type • The returnstatement specifies the value that should be returned, which must conform with the return type of the method.

  14. Method Context • The getHours() and hourElapsed() methods are instance methods, which means they act on a particular instance of the class • They cannot be invoked “out of the blue”. They must act on a particular object: Clock c = new Clock(); getHours(); // of which clock? c.getHours(); // will return 0 • An instance method is executed in the context of the object it acts upon.

  15. class ClockTest { public static void main(String[] args) { Clock swatch = new Clock(); Clock seiko = new Clock(); System.out.println(swatch.getHours()); // 0 System.out.println(seiko.getHours()); // 0 swatch.hourElapsed(); System.out.println(swatch.getHours()); // 1 System.out.println(seiko.getHours()); // 0 } }

  16. The this Reference • When appearing inside an instance method, the this keyword denotes a reference to the object that the method is acting upon. • The following are equivalent: public int getHours() { return hours; } public int getHours() { return this.hours; } • We will soon see why this is useful

  17. Method Parameters • A method can be defined to accept zero or more parameters • Each parameter in the parameter list is defined by its type and name • The parameters in the method definition are called formal parameters • The values passed to a method when it is invoked are called actual parameters • The name of the method together with the list of its formal parameters is called the signature of the method

  18. public class Clock { // ... /** * Sets the time read by the clock. * If one of the paramenters is not in the allowed * range, the call will not have any effect on the * clock. * @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 void setTime(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; } // no effect if input is illegal } }

  19. Passing Parameters • When a parameter is passed, a copy of the value is made and assigned to the formal parameter: Clock beritling = new Clock(); int lunchHour = 12; breitling.setTime(lunchHour,32,14); hours = lunchHour minutes = 32 seconds = 14

  20. Passing Parameters • Both primitive types and object references can be passed as parameters • When an object reference is passed, the formal parameter becomes an alias of the actual parameter

  21. /** * A bank account. */ public class BankAccount { private long accountNumber; // The balance in dollars private float balance; /** * Constructs a new empty account. */ public BankAccount(long accountNumber) { this.accountNumber = accountNumber; this.balance = 0; } // continued in next slide... }

  22. /** * Deposites a given amount into the account. */ public void deposit(float amount) { // ... perhaps perform some security checks balance = balance + amount; } /** * Withdraws a given amount from the account. */ public void withdraw(float amount) { // ... perhaps perform some security checks balance = balance - amount; } // continued in next slide...

  23. /** * Transfers a given amount into another bank account */ public void transfer(float amount, BankAccont other) { // ... perhaps perform some security checks this.withdraw(amount); other.deposit(amount); } BankAccount gadiAccount = new BankAccount(1398723); BankAccount saritAccount = new BankAccount(1978394); gadiAccount.deposit(500); // gadi’s balance = 500 gadiAccount.transfer(700,saritAccount); // gadi’s balance = -200, sarit’s balance = 500

  24. Constructor Overloading • A class can define several constructors -- several ways to initialize an instance of this class • These constructors differ by the number and type of parameters they get. • When we construct an object, the compiler decides which constructor to invoke • A constructor with no parameters is called a default constructor

  25. /** * 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; } }

  26. 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: in no way may an object be initialized to an inconsistent state! • What is an inconsistent state in a clock?

  27. Visibility Modifiers • We accomplish encapsulation through the appropriate use of visibility modifiers • A modifier is a Java reserved word that specifies particular characteristics of a programming construct • We've used the modifier final to define a constant • Java has three visibility modifiers: public, private, and protected • We will discuss the protected modifier later

  28. Visibility Modifiers • A class can be defined either with the public modifier or without a visibility modifier. • If a class is declared as public (has public visibility) 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 classes can use this class. We will discuss default visibility of classes in a later lecture. • Classes that define a new type of objects, that are supposed to be used anywhere, should be declared public.

  29. Visibility Modifiers • We use the generic term member to describe a variable, method or constructor of the class. • Members of a class can be declared as private, protected, public or without a visibility modifier. • Members that are declared without a visibility modifier have default visibility. We will discuss default and protected visibility in later lectures.

  30. Public Visibility • Members that are declared as public can be accessed from any code that can access the class of the member • We expose methods that are part of the interface of the class by declaring them as public • Example: the methods getHours(), hourElapsed()andsetTime() are part of the interface of class Clock so we define them as public. • We do not want to reveal the internal representation of the object’s data. So we usually do not declare its state variable as public.

  31. Private Visibility • A class member that is declared as private, can be accessed only by code that is within the class of this member. • We hide the internal implementation of the class by declaring its state variables and auxiliary methods as private. • Data hiding allows us to achieve good encapsulation. • Note, that the hiding is on the level of classes (code) and not on the level of objects: from within a BankAccount object, any private member of a different BankAccount object can be accessed.

  32. /** * Transfers a given amount into another bank account */ public void transfer(float amount, BankAccont other) { // ... perhaps perform some security checks this.withdraw(amount); other.deposit(amount); // an alternative way of doing the same thing: // other.balance = other.balance + amount }

  33. // Example of illegal access class BankAccountTest { public static void main(String[] args) { BankAccount victim = new BankAccount(2398742); victim.balance = victim.balance - 500; // this will not compile! } }

  34. The Static Modifier • 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. • We can write a class that is a collection of static methods. Such a class isn’t meant to define a new type of objects. It is just used as a library for utilities that are related in some way.

  35. 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) { // ... } // ... }

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

  37. Division into Methods // Prints all the prime numbers public class Primes { public static void main(String[] args) { OutputWindow out = new OutputWindow(); int number = 0; while (true) { number = number + 1; if (isPrime(number)) out.println(number); } } // Returns true iff number is prime public static boolean isPrime(int number) { // determines if number is prime } }

  38. 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 for the class. • We have already seen such usage - constants of a class (final static)

  39. Static Variables - Example /** * A bank account. */ public class BankAccount { private long accountNumber; // The balance in dollars private float balance; private static int numberOfAccounts = 0; // continued in next slide... }

  40. Static Variables - Example public BankAccount(long accountNumber) { this.accountNumber = accountNumber; this.balance = 0; numberOfAccounts = numberOfAccounts + 1; } public static int getNumberOfAccounts { return numberOfAccounts; }

  41. Static Methods and Variables • Static methods cannot reference instance variables, because instance variables don't exist until an object exists • Similarly the reference this has no meaning inside a static method, thus its use inside a static method is not allowed. • However, static methods can reference static variables or local variables (within the method)

  42. Documentation • Let’s look at a complete overview of class clock • Note that documentation is an integral part of the class • Any documentation which is part of the interface begins with /** (double asterick) and ends with */ • To use the class, we need not (and should not) look at the code. All that is needed is the class API.

  43. API Documentation • Your classes are often intended to be used by other programmers • Programmers that use your class are not interested in the way it is implemented. They want to use it as a whole and are only interested in what it does and how to use it. • API (Application Programmer Interface) documentation is a description of the interface of the class intended for the application programmer who wants to use it.

  44. API Documentation • Java gives a special tool - the javadoc - as part of the JDK for the generation of API documentation for your classes. • The javadoc generates .html documents that summarizes the interface of the classes. • In addition Java define a special type of comments, called documentation comments which are used by the javadoc. • Documentation comments are added between /** … */ symbols. We’ve already used them for the classes use showed in this lecture

  45. Generating Javadoc

  46. What should you comment? • You should put a documentation comment for any member of the class which is part of its interface and for the class itself. • All public constructors and methods should documentation comments • Private methods are not part of the interface of the class, thus javadoc skips them.

  47. API Documentation • Remember that documentation comments are written for programmers who use your class as a whole. They should describe only what the class does and how to use it and not how it is implemented. • Documentation comments should be short and descriptive. • They should be written in a simple language • They should be accurate • Assume that the reader doesn’t know anything about your class

  48. API Documentation Tags • Documentation comments text can include HTML tags. • Documentation comments can also include tagged paragraphs that give a standard way to document several features of the interface such as method parameters, return values, etc. • A tagged paragraph begins with the symbol @ followed with a tag keywords. Tags: @see, @author, @version, @param, @return, @exception.

  49. Naming • The names you use for your class and for its public methods are part of the class API. • Good descriptive naming are crucial for a clear API. • General rules about naming: • Follow the Java conventions • Use descriptive names • Long enough, not unnecessary long • Consist of words in English with no abbreviations • Use a dictionary

More Related