1 / 62

Constructors Method Overloading Class Members Static Variables Static Methods

Constructors Method Overloading Class Members Static Variables Static Methods Libraries and Packages Math Class Random Class Decimal Format Class Wrapper Classes Enumerated Types More on Packages. Creating Objects .

Télécharger la présentation

Constructors Method Overloading Class Members Static Variables Static Methods

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. Constructors Method Overloading Class Members Static Variables Static Methods Libraries and Packages Math Class Random Class Decimal Format Class Wrapper Classes Enumerated Types More on Packages

  2. Creating Objects • The process of creating an object from a class is called instantiation. • An object is an instance of a particular class • The new operator is typically used to create an object • Allocates the memory required to the object • Calls the constructor of the class to initialize the internal data of the new object • Returns address in memory where the object is located Example Clock myClock = new Clock();

  3. Constructors • A constructor is a special method that is used by the new operator to initialize the instance variables of the new object being created • A constructor has the same name as its class and may or may not take parameters A constructor without parameters is known as a default constructor public Clock() { this.time = (int) Math.random()*86400; this.location = "Unknown"; } Initialize instance data time to a random number between 0 and 86400

  4. Constructor Header public private constructor name parameter list public className ([type parName1[,type parName2…]) The parameter list specifies the type and name of each parameter. Parameters are used to pass the initial values of the instance variables The constructor’s name must match the Class name. • A constructor has no return type in its declaration

  5. Constructor Body • The constructor should initialize all instance variables of the object • If the constructor does not initialize an instance variable explicitly, Java assigns it a default value according to its data type: • Numerical instance variables to zero • Boolean instance variables to false • Class type instance variables to null

  6. 5432 time location myClock Constructors • A class may have several constructors as long as they differ in • Number or data type of the constructor parameters Random number public Clock() { this.time = (int) Math.rand()*86400; this.location = "Unknown"; } … “unknown" public class MyDemo { public static void main (String [] args) { Clock myClock = new Clock (); … } }

  7. Constructors • Write a constructor that takes time as a parameter and initializes the time to specified value. It should sets the location to “Unknown”.

  8. 43200 time location myClock Clock Class public Clock() { this.time = (int) Math.rand()*86400; this.location = "Unknown"; } public Clock(int seconds) { if (seconds >= 0 && seconds < 86400) this.time=seconds; this.location = "Unknown"; } “unknown" MyDemo Class public class MyDemo { public static void main (String [] args) { Clock myClock = new Clock (43200); … } }

  9. Exercise • Write a constructor that takes location (string) and time (int) as parameters and sets the time and location of the object to specified values.

  10. //default constructor public Clock() { this.time = (int) Math.rand()*86400; this.location = "Unknown"; } //constructor with one parameter (time) public Clock(int seconds) { if (seconds >= 0 && seconds < 86400) this.time=seconds; this.location = "Unknown"; } //constructor with two parameters public Clock(String location, int seconds) { this.setTime(seconds); this.setLocation(location) } You can call a method from the constructor to set the value of the instance variables

  11. Constructors • Within a constructor you can call another constructor of the class by using only the keyword this and a list of actual parameters to the constructor you want to execute: public Clock(String location, int seconds) { this.setTime(seconds); this.setLocation(location) } public Clock (String location) { this(location,0); }

  12. More on Constructors • A constructor is a special method that is used to set up an object when it is initially created • A constructor has the same name as the class • A constructor has no return type in its declaration • A constructor never returns a value • A constructor cannot be called again once the object is created. • Usually, the visibility of a constructor is public

  13. Constructors Method Overloading Class Members Static Variables Static Methods Libraries and Packages Math Class Random Class Decimal Format Class Wrapper Classes Enumerated Types More on Packages

  14. Overloading Methods • Signature of a method consists of its name and the number and type of its parameters. Signature: reset, int, int , int public void reset(int hr, int min, int sec) { if ((hr >= 0 && hr < 24) && (min>=0 && min <60) && (sec >=0 && sec <60)) { this.time = hr * 3600 + min*60 + sec; } } • Java allows you to write in the same class methods with the same name, as long as they differ in their signature • There are not two methods that share the same name with the same signature • Method overloading refers to the ability of defining several methods sharing the same name but either have different numbers of parameters or have corresponding parameters with different types.

  15. Overloading Methods Signature: int • public void reset(int hr) • { • if ((hr >= 0 && hr < 24) ) • { • this.time = hr * 3600 + this.time % 3600; • } • } Signature: int, int public void reset(int hr, int min) { if ((hr >= 0 && hr < 24) && (min >= 0 && min < 60) ) { this.time = hr * 3600 + min * 60 + this.time % 60; } } We say that the method reset is overloaded

  16. Overloading Methods Could we include the following method in the class Clock? public void reset(int min, int sec) { if ((min >= 0 && min < 60) && (sec >= 0 && sec < 60) ) { this.time = this.time – this.time % 3600 + min * 60 + this.time % 60; } } NO!!!!! There is another method in this class sharing the same name and same signature

  17. Exercise: • Write a method called reset, that overloads the other reset methods. This method takes two parameters, hour (int ) and isAM (boolean), and sets the hour portion of time to specified value accordingly. • Ex: • myClock.setTime (3660) // time = 3660  it is 1:01:00 A.M. • myClock.reset ( 4 , true ) // time = 14460  It is 4:01:00 AM • myClock.setTime (54300) // time = 54300  it is 3:05: PM • myClock .reset(4, false) // time =14700  it is 4:05 P.M now

  18. Overloading Methods Signature: int , boolean public void reset(int hr, boolean isAm) { if ((hr >= 1 && hr <= 12) ) { this.time = ( isAm ? hr : (12 + hr)%24)*3600 + this.time % 3600; } } Could we include the following method in the class Clock? YES!!!!! There isn’t any other method called reset with this signature

  19. More on Constructors • A class can have more than one constructor as long as they differ in their signature // // Default Constructor // public Clock() { this.time = 0; this.location = "Unknown"; } Signature: public Clock(String location, int seconds) { this.setTime(seconds); this.setLocation(location) } Signature: String, int

  20. More on constructors • A class can have more than one constructor as long as they differ in their signature Can we define this constructor in the class? // // Default Constructor // public Clock() { this.time = 0; this.location = "Unknown"; } public Clock(String location, int seconds) { this.setTime(seconds); this.setLocation(location) } public Clock(String location, int hour) { this.setLocation(location); if (hour >=0 && hour <24) this.time = hour*3600; } NO!!! There is another constructor with the same signature

  21. Exercise • Write a class called Money with two instance variables dollars and cents of type integer. • Write the following methods and constructors • Money() : constructor • Money(int dollars, int cents): constructor • getDollars: get method for dollars. • setDollars: set method for dollars. • getCents: get method for cents. • setCents: set method for cents. • toString: String representation of Money $__.__ • add: add the given money object to this money object • compareTo: compare this money object with a given money object

  22. Exercise: • Write a class called Person with three instance variables: name, email and age. • Write the following methods: • Person () • Person (String name) • Person (String name, String email, int age) • getName • setName • getEmail • setEmail • getAge • setAge • sayHello: prints out “Hello my name is …” • toString: Prints the name, email and age

  23. Constructors Method Overloading Class Members Static Variables Static Methods Libraries and Packages Math Class Random Class Decimal Format Class Wrapper Classes Enumerated Types More on Packages

  24. int static SECSXMIN = 60intstatic SECXDAY = 86400intstatic SECXHR = 3600intstatic numberOfClocks=0 int time; String location; Class - Structure • A class can contain data declarations and method declarations • Data and methods of a class are the members of the class • Class members (Static members) • Data and methods of the class • Instance members • Data and methods of the objects of the class Class Data (Static data) Data declarations (Attributes) Instance Data Class Methods (Static methods) Method declarations (Behavior) Instance Methods

  25. 21600 18000 43200 time time time location location location Clock int static SECSXMIN = 60intstatic SECXDAY = 86400intstatic SECXHR = 3600intstatic numberOfClocks = 0 int time; String location OOP - Objects and Classes “New York” Instance methods, and variables belong to the objects. “London" “Chicago" Class members belong to the class.

  26. Static Class Members • To declare a class member, we use the modifier static after the visibility modifier. • It associates the method or variable with the class rather than with an object of that class publicclass Clock { // Class member data public final staticint SECXMIN = 60; public final staticint MINXHOUR = 60; public final static int SECXHOUR = 3600; public final staticint NOON = 12; public final staticint HRXDAY = 24; public final staticint SECXDAY = 86400; public final static intSEXXHALFDAY = 43200; private static intnumberOfClocks= 0; // Instance member data privateint time = 0; private String location ... // return the number of Clock Objects public static inthowMany(){ …. returnnumberOfClocks; } ... } Class member data Class member methods

  27. Member Variables • Instance Member Variables • Each object has its own collection of instance variables that defines the object’s data space. • The values of instance data define the internal state of an object • Instance variables can only be accessedwithin instance methods • Instance variables exists as long as the object exists • Class Member Variables • Usually represent properties of the class itself • Belong to the class,only one copy of the variable exists • Static variables are shared by all objects instantiated from the class. • Instance and class methods can access the static variables of a class

  28. publicclass Clock { // Class member data public final staticint SECXMIN = 60; public final staticint MINXHOUR = 60; public final staticint HRXDAY = 24; public final static int SECXHOUR = 3600; public final staticint SECXDAY = 86400; private static int numberOfClocks= 0; // Instance member data privateint time = 0; private String location=""; public Clock() { this.time = 0; this.location = "Unknown"; numberOfClocks++; } public Clock(String location, int seconds) { this.setTime(seconds); this.setLocation(location) numberOfClocks++; } // return the number of Clock Objects public static int howMany() { return numberOfClocks; } } static variables(Class member variables) Accessing a static variable in a constructor static method

  29. Static Member Variables • Public Member Variables (public static) are accessed by the name of the class. Example: int secondsPerDay = Clock.SECXDAY ; int secondsPerMinute = Clock.SECXMIN ; • Only static constant variables should be declared public • Allow client code to access their value • But, a value of a static constant can not be changed so it does not violate encapsulation

  30. Static Member Variables • Static Member Variables that are not constant must be declared private to prevent uncontrolled access or alteration. • Access and alteration to private static variables must be done via accessors and mutators // return the number of Clock Objects public static int howMany(){ return numberOfClocks; }

  31. Static Methods • A static method • belongs to the class • if public can be invoked only through its class name • a static method can ONLY call another static method declared within the same class • can only access static data, parameters and local variables declared within the method public static int howMany() { return numberOfClocks; } public static boolean isValidTimeInSeconds(int number) { return number >= 0 && number < SECXDAY; }

  32. Static Methods • A public static method is invoked in a client through the name of the class int clockPopulation = Clock.howMany(); System.out.println (“Input a number “); int number= keyboard.nextInt(); if (Clock.isValidTimeInSeconds(number)) { System.out.println(number + " is a valid number of seconds in a day"); } else { System.out.println(number + " is not a valid number of seconds in a day"); }

  33. Static Methods • A static method can be called from an instance method, but not the other way around public static boolean isValidTimeInSeconds(int number) { return number >= 0 && number < SECXDAY; } public void setTime (int newTime) { if (isValidTimeinSeconds(newTime)) this.time = newTime; }

  34. Class (Static) Members • Recommendations • Class (static) Member variables • to keep track of some information shared by all objects of the class. • To represent properties of the class such as constants used by all objects of that class • Class (static) methods • Methods that used only static data, its parameters and local data to compute a value • A static method can call any other static method but not an instance method • An instance method can call a static method if needed • Use static variables/methods only when justified.

  35. Main method • The main method is a static method in a class • You can call other static methods define in the same class to help the main method to solve the problem • Each of these static method solves a sub-task • Each of these static methods could be private • It is a good practice to write client codes that split the main method in several static methods, each focusing in one task

  36. Main Method public class ClockDriver { public static void main(String[] args ) { Clock clock1 = new Clock(); Clock clock2 = new Clock(); Clock clock3 = new Clock(); clock1.setLocation("London"); clock2.setLocation("Atlanta"); areEqual(clock1,clock2); areEqual(clock2,clock3); areEqual(clock3,clock1); } private static void areEqual(Clock aClock,Clock anotherClock) { if (aClock.equals(anotherClock)) System.out.println(aClock + " has the same data as "+ anotherClock) else System.out.println(aClock + " does not have the same data as "+ anotherClock); } }

  37. Constructors Method Overloading Class Members Static Variables Static Methods Libraries and Packages Math Class Random Class Decimal Format Class Wrapper Classes Enumerated Types More on Packages

  38. Class Libraries • A class library is a collection of predefined classes that we use during program development. • A class library is called a Application Programming Interface (API) • The Java standard class library is part of any Java development environment • The classes System , String and Scanners are part of the Java standard class library

  39. Package java.lang java.applet java.awt javax.swing java.net java.util javax.xml.parsers Purpose General support Automatically available in every Java Program Creating applets for the web Graphics and graphical user interfaces Additional graphics capabilities Network communication Utilities XML document processing Packages • Classes in a class library are organized in packages • Packages that begin with "java" are part of the Java Standard class library • Some of the packages in the standard class library are:

  40. A package is a collection of classes grouped together into a folder. • Each class in the folder should include a package statement before the class header package factorion; package general.utilities; • The package statement indicates that a class belongs to a package

  41. The import Declaration • To use a class in a given package, you must use the import statement and the package name. • import statements must be written prior any class declaration • java.lang package is imported automatically • Classesin the same folder as the program you are compiling are imported automatically

  42. import java.util.Scanner; import java.awt.*; public class Demo { } public static void main (String[] args) { } … Scanner keyboard=new Scanner(System.in) ….. The import Declaration importing a specific class of a package importing all classes in a particular package using the * wildcard character

  43. Constructors Method Overloading Class Members Static Variables Static Methods Libraries and Packages Math Class Random Class Decimal Format Class Wrapper Classes Enumerated Types More on Packages

  44. Formatting Output • The class Decimal is a class of the Java standard class library that provides formatting capabilities • The DecimalFormat class format values based on a pattern. • The class DecimalFormat is part of the text package and must be imported in your Java application

  45. Formatting Output • The DecimalFormat class can be used to format a floating point value according to a customized formatting pattern. • Formatting pattern is a combination of format symbols "0,000,000.00" "###.###"

  46. Formatting Output • Create a DecimalFormat Object • Use the new operator. • The constructor of the class takes as argument a string that represents the formatting pattern. DecimalFormat myZerosFmt = new DecimalFormat("000,000.00"); DecimalFormat myFmt = new DecimalFormat("###,###.00"); • In the program, invoke the method format of the DecimalFormat object • returns a string containing the number in the appropriate format. myZerosFmt.format(12.1) // returns "000,012.10" myFmt.format(12.1) // returns "12.10“ myFmt.format (2.1) // returns “2.10” myFmt.format (123456.6) // returns “123,456.60”

  47. Outline Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Enumerated Types

  48. Wrapper Classes • The java.lang package contains wrapper classes that correspond to each primitive type:

  49. age 22 salary 1000000.96 Wrapper Classes • Use the new operator to create a wrapper object Integer age = new Integer(22); Double salary = new Double(1000000.96); • You can store a value of a primitive type in a type-wrapper object whenever an object is required.

  50. Wrapper Classes – Instance Methods • Wrapper objects can execute instance methods • toString() - Returns the String representation of a wrapper object Integer objAge = newInteger(23); Double objBalance = newDouble(1260.85); String ageStr= objAge.toString(); • intValue() – returns the equivalent int from an Integer object • The classes Float, Double, Long and Characters have the methods floatValue, doubleValue, longValue respectively int age = objAge.intValue(); double price = 0.9*objBalance.doubleValue();;

More Related