ECE 122 Engineering Problem Solving with Java Lecture 5 Anatomy of a Class
Outline Problem: How do I build and use a class? Need to understand constructors A few more tools to add to our toolbox Formatting data Wrapper classes Putting it all together Understanding all the details of building and using classes Private and public data and methods
The Math Class The Math class is part of the java.lang package The Math class contains methods that perform various mathematical functions These include: absolute value square root exponentiation trigonometric functions
The Math Class The methods of the Math class are static methods (also called class methods) Static methods can be invoked through the class name no object of the Math class is needed value = Math.cos(90) + Math.sqrt(delta); No need to instantiate the object here (built-in) Useful for various math functions
Wrapper Classes The java.lang package contains wrapper classes that correspond to each primitive type: Primitive Type byte short int long float double char boolean void Wrapper Class Byte Short Integer Long Float Double Character Boolean Void
Wrapper Classes The following declaration creates an Integer object which represents the integer 40 as an object Integer age = new Integer(40); Wrapper classes used references Primitive classes do not use references Mem Loc 1089 688 40 Mem Loc 1089 Contents of memory
Wrapper Classes Wrapper classes contain methods that help manage the associated type intvalue longvalue Prevents the need to manage primitive types The Integer class contains a method to convert an integer stored in a String to an int value: num = Integer.parseInt(str);
Classes and Objects An object has state (declarations) and behavior (methods) Consider a coin State can be defined as heads or tails Behavior is that it can be flipped We can represent a coin in software by designing a class called coin that models this state and behavior The class serves as the blueprint for a coin object We can then instantiate any number of coins that we need for a program
Classes A class can contain data declarations and method declarations Already seen this many times int size, weight; char category; Data declarations Method declarations
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 coin constructor used create an object which will generate a random variable public coin() { /* Create an instance of a random object */ rnd = new Random(); } Any unusual features?
Instance Data The facevalue variable in the Die class is called instance data Each instance (object) that is created has its own version of it A class declares the type of the data, but it does not reserve any memory space for it Every time a Die object is created, a new facevalue variable is created as well The objects of a class share the method definitions Each object has its own memory space
Instance Data We can depict the two Die objects from the RollingDice program as follows: die1 facevalue 5 die2 facevalue 2 Each object maintains its own facevalue variable, and thus its own state
Method Declarations A method declaration specifies the code that will be executed when the method is invoked (called) When a method is invoked, the flow of control jumps to the method and executes its code When complete, the flow returns to the place where the method was called and continues The invocation may or may not return a value, depending on how the method is defined Remember that software is sequential. Only one thing is happening at a time
Method Control Flow If the called method is in the same class, only the method name is needed compute mymethod mymethod();
Method Control Flow The called method is often part of another class or object main doit helpme obj.doit(); helpme();
Method Header A method declaration begins with a method header char calc (int num1, int num2, String message) method name parameter list return type The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal parameter
Method Body The method header is followed by the method body char calc (int num1, int num2, String message) { int sum = num1 + num2; char result = message.charat (sum); } return result; The return expression must be consistent with the return type sum and result are local data They are created each time the method is called, and are destroyed when it finishes executing
The return Statement The return type of a method indicates the type of value that the method sends back to the calling location A method that does not return a value has a void return type A return statement specifies the value that will be returned return expression; Its expression must conform to the return type
Parameters When a method is called, the actual parameters in the invocation are copied into the formal parameters Formal parameters located in method header ch = obj.calc (2, count, "Hello"); char calc (int num1, int num2, String message) { int sum = num1 + num2; char result = message.charat (sum); } return result;
Data Scope The scope of data is the area in a program in which that data can be referenced (used) Data declared at the class level can be referenced by all methods in that class Data declared within a method can be used only in that method Data declared within a method is called local data In the Die class, the variable result is declared inside the tostring method It is local to that method and cannot be referenced anywhere else
Local Data Local variables can be declared inside a method Method creates automatic local variables when the method is invoked When the method finishes, all local variables are destroyed (including the formal parameters) Instance variables, declared at the class level, exists as long as the object exists new indicates data is allocated and stays allocated until garbage collected. Local data in methods disappear when the method disappears
Formatting Output It is often necessary to format values in certain ways so that they can be presented properly The Java standard class library contains classes that provide formatting capabilities The NumberFormat class allows you to format values as currency or percentages The DecimalFormat class allows you to format values based on a pattern Both are part of the java.text package
Enumerated Types Java allows you to define an enumerated type, which can then be used to declare variables An enumerated type establishes all possible values for a variable of that type The values are identifiers of your own choosing The following declaration creates an enumerated type called Season enum Season {winter, spring, summer, fall}; Any number of values can be listed
Enumerated Types Once a type is defined, a variable of that type can be declared Season time; and it can be assigned a value time = Season.fall; The values are specified through the name of the type Enumerated types are type-safe you cannot assign any value other than those listed
Ordinal Values Internally, each value of an enumerated type is stored as an integer, called its ordinal value The first value in an enumerated type has an ordinal value of zero, the second one, and so on However, you cannot assign a numeric value to an enumerated type, even if it corresponds to a valid ordinal value
Enumerated Types The declaration of an enumerated type is a special type of class, and each variable of that type is an object The ordinal method returns the ordinal value of the object The name method returns the name of the identifier corresponding to the object's value
Summary We ve now learned most of what we need to know for classes Important concepts: constructors, parameters, return values, how computer memory is used Many objects can be created, each with their own memory Next time: Problem solving Solving a problem from definition to implementation