Presentation is loading. Please wait.

Presentation is loading. Please wait.

Classes with multiple methods Part 1. Review of classes & objects Early on, we learned that objects are the basic working units in object-oriented programs.

Similar presentations


Presentation on theme: "Classes with multiple methods Part 1. Review of classes & objects Early on, we learned that objects are the basic working units in object-oriented programs."— Presentation transcript:

1 Classes with multiple methods Part 1

2 Review of classes & objects Early on, we learned that objects are the basic working units in object-oriented programs –Classes describe objects –Objects are instances of classes A programmer-defined class is any class that isn’t in the Java API

3 Class methods & data A class definition generally consists of: –A set of methods that perform tasks –A set of data that can be manipulated by these methods To design a class: –Think about the thing we want to model –Come up with a list of tasks we want that thing to do

4 Example: a thermometer A thermometer is an instrument that measures temperature and displays its reading The set of operations is: –Measure temperature –Display temperature

5 Enhanced thermometer We’re going to look at a thermometer with somewhat enhanced capabilities Instead of just displaying the temperature measured, the enhanced thermometer can display its measurement in three different scales: Celsius, Fahrenheit, and Kelvin

6 Data members Class-wide data are stored in variables or constants Such data belong to an object (or to a class) and not to any particular method within the object Such data are accessible to all methods of the class A thermometer object needs to have a variable to store its unique temperature reading, and constants to use for converting the value between the 3 scales

7 Data members in BetterTherm class The class-wide data declarations appear at the beginning of the class: public class BetterTherm { private int kelvinTemp; private final static int CFACTOR = 273; private final static int RANGE = 101; private final static int FCONVI = 32; private final static double FCONVD = 1.8;

8 Instance variables There is one variable declared on the previous slide: private int kelvinTemp; –This is an instance variable; that is, it belongs to an instance of the class (in other words, an object) –Every instance of the class will have its own copy of this variable, so every object of this type could have a unique temperature value

9 Class constants All of the constants, such as the one below, differ from the variable not only because they are constants, but because the keyword static in their declaration indicates that they belong to the entire class, not to any particular class instance: private final static int CFACTOR = 273;

10 Class constants If a class member (either data or method) is declared static, its existence is independent of any particular object: –All objects of the class type share such members, rather than having their own copies –The class member exists even if there are no class instances; this is how it is possible for us to access the PI constant from the Math class even though we never create Math objects

11 Visibility modifiers The keywords public and private are used to indicate whether or not access to the declared item is restricted to class members If a variable, constant, or method is declared private, then it can only be “seen” by members of its class If declared public, visibility extends outside the class In most cases, variables are declared private, while methods are declared public If no visibility modifier is given, the default is private

12 Defining methods In the examples we’ve seen in the past, each class contained a single method, named main For this class, we’ll define a more conventional set of methods: –Constructor: a method that defines the default characteristics of an object –Accessors: methods that provide access to the data values in the class –Mutators: methods that change the data values in a class

13 Constructor The constructor for a Java class is a special method used to initialize data members of the object being created It has the following unique characteristics: –Always public –No return type –Same name as the class The next slide shows a constructor for the BetterTherm class

14 BetterTherm Constructor public BetterTherm () { Random temp = new Random(); kelvinTemp = Math.abs(temp.nextInt()); kelvinTemp = kelvinTemp % RANGE + CFACTOR; // initializes the temperature to somewhere between // 273K and 373K - the freezing point and boiling point // of water, respectively, on the Kelvin scale }

15 BetterTherm Constructor The purpose of the constructor is to set a default value for the instance variable kelvinTemp The default value is a random number between 273 and 373 methods within a class have access to variables and constants declared as part of the same classBecause the method (BetterTherm) and the variable (kelvinTemp) are members of the same class, there is no need to pass an argument to BetterTherm (the method); methods within a class have access to variables and constants declared as part of the same class For the same reason, the constructor has access to CFACTOR and RANGE, two of the class constants

16 Local variables Besides kelvinTemp, there is another variable used in the constructor: the random number generator object, temp This variable is declared within the BetterTherm method localSince it is declared within the block of code comprising the body of the method, we say that this variable is local to the method

17 Scope of identifiers The locality of the temp variable is referred to as its scope; the more local the scope, the more restricted its accessibility A local variable can only be referenced within the block where it’s declared The scope of instance variables and class constants is wider; we can refer to these from anywhere within the class, as we have already seen

18 Accessor methods Accessor methods provide a kind of a window into the private world of the class –An analogy: your thoughts are private, but you can give the outside world access to them by putting your thoughts into words –Even though the world can now “see” your thoughts, they still belong to you, and only you can change your mind In a similar way, accessor methods allow the world to see the values of private data members of an object, but only the object can change these values (via mutator methods)

19 Accessor methods Because the purpose of an accessor is to make a value visible, this type of method always has a return type other than void return statementSuch methods must contain a return statement –Typically the last statement in a method –When this statement executes, the method ends –The value returned is represented by an expression which must evaluate to a result of the return type of the method

20 Two example accessors from BetterTherm // return Kelvin temperature public int getKelvin () { return kelvinTemp; } // Convert to Celcius & return public int getCelcius () { return kelvinTemp - CFACTOR; } Both methods have an int return type, so each one has a return statement containing an integer expression. Simple accessor methods like this are sometimes called “getter” methods.

21 One more example We declare local variable fTemp to hold the return value The method could have been written with just a return statement, but it’s a little easier to read this way // Convert to Fahrenheit & return public int getFahrenheit () { int fTemp; // Fahrenheit temperature to be returned fTemp = (int)(FCONVD * getCelcius()) + FCONVI); return fTemp; }

22 The general model for a method The generic syntax for a method is: Modifier(s) returnType identifier (parameter(s)) { method body return statement (if needed) } Where: Modifiers include public, private, and static returnType is a simple type, class type, or void A return statement is necessary unless the method is declared void

23 Static methods As we have seen, static constants belong to the class, rather than to an object We have seen numerous examples of Java methods that are called using messages associated with classes rather than objects (the Math methods, JOptionPane methods, etc.) These are examples of static methods

24 Static methods static methods can only access other static class membersStatic methods differ from non-static methods in another important way; static methods can only access other static class members (variables, constants or methods) The main method is always declared static; in order to use the main method to test non-static members of the class, you must declare an object of the class type and call the methods from that object

25 A main method for BetterTherm public static void main (String [] args) { BetterTherm bt1, bt2, bt3; bt1 = new BetterTherm(); bt2 = new BetterTherm(); bt3 = new BetterTherm(); System.out.println ("The three thermometers are reading as follows:"); System.out.println ("\tK\tC\tF"); System.out.println ("1)\t" + bt1.getKelvin() + "\t" + bt1.getCelsius() + "\t" + bt1.getFahrenheit()); System.out.println ("2)\t" + bt2.getKelvin() + "\t" + bt2.getCelsius()+ "\t" + bt2.getFahrenheit()); System.out.println ("3)\t" + bt3.getKelvin() + "\t" + bt3.getCelsius() + "\t" + bt3.getFahrenheit()); }

26 Main method The main method presented on the previous slide creates three thermometer objects, then shows their temperature readings in the three different scales The output looks something like this: The three thermometers are reading as follows: KCF 1)35077170 2)37198208 3)32249120

27 Main method The main method can either be declared as part of the class or in a separate tester class An example of a tester class is shown below: public class TestTherm { public static void main (String [] args) { // same body as previously shown }


Download ppt "Classes with multiple methods Part 1. Review of classes & objects Early on, we learned that objects are the basic working units in object-oriented programs."

Similar presentations


Ads by Google