460 likes | 592 Views
Using and Making Classes. BCIS 3680 Enterprise Programming. Overview. Using Classes Class and object Using premade classes for input and output Display output: System, JOptionPane classes Format output: Decimal Format, NumberFormat classes
E N D
Using and Making Classes BCIS 3680 Enterprise Programming
Overview • Using Classes • Class and object • Using premade classes for input and output • Display output: System, JOptionPane classes • Format output: Decimal Format, NumberFormat classes • Handling Input: Wrapper classes, e.g., Integer, Double • Processing: Math class • Building Your Own Classes • Members of a class • Variables (instance and static) • Methods (instance and static) • Storing and accessing values in an object • Constructor methods • Getter and setter methods
Class • A class defines a number of properties (variables) and actions/behaviors (methods). • An object created from this class will have those variables and methods. • Variables are used to store data. • Methods are used to specify action.
Object vs. Class • Object reference • Identifier (name) of the object • Holds the address of the object • A class is a template for making objects. • An object is an instance of a class. • The process of creating an object out of a template (class) is called instantiation, “creating an instance of the class”, etc. • Remember the naming convention: • The name of a class starts with an uppercase letter. • The name of a variable starts with a lowercase letter.
Creating Objects • Two things required to create an object: • Declaring an object reference for the new object, ClassNameobjRef; e.g., Student cobStudent; • Using the new keyword to actually create the object, objRef = new ClassName([arguments]); e.g., cobStudent = new Student("ITDS", "Undergrad"); • The two steps may be combined into one: ClassNameobjRef = new ClassName([arguments]); Student cobaStudent = new Student("ITDS", "Undergrad"); // One step
Using Objects • To use an object’s variables and methods, you use the “.” operator (dot notation). objectName.variableName cobStudent.dept = "Marketing"; objectName.methodName([arguments]); cobStudent.regClass("BCIS3680");
Organization of Classes • Related classes are organized into packages. • Java SE comes with a number of commonly used packages. • To use Class A in Class B, you need to have an import statement for Class A at the beginning of Class B. • The only exception is the classes in the java.lang package, which can be used by all other classes without an import java.lang; statement. • Two ways to write the import statement: • Specifically import the name of the particular class you want to use, e.g., import java.util.Scanner;. • Import the entire package the class belongs to, e.g., import java.util.*;. • All other classes in that package are accessible now.
Packages of “Premade” Classes • Classes are grouped in packages according to functionality by using the package keyword. • The following packages ship with the Java language:
The System Class • The Systemclass is in thejava.langpackage, so it does not need to be imported. • Two useful staticconstants (variables with constant value) of the Systemclass: • in represents the standard input device (the keyboard by default). • out represents the standard output device (the Java console by default). • Examples: Scanner scan = new Scanner(System.in); System.out.println("Hello");
Using System.out Example: System.out.print("The answer is "); System.out.println(3); The output is: The answer is 3
Using Dialog Boxes • The JOptionPane class is in the javax.swing package. • You must import it. • Static methods are provided for input and output dialog boxes. • For input dialog boxes, return value is a String, so numeric input needs to be converted (using methods such as parseInt() or parseDouble()).
Message Dialog Box • Displays a message and then waits until the user press OK: showMessageDialog(Component parent, Object message, String title, intmessageType) • parent – use null for projects • mesage – the message you want to display. A string is fine as it is an object. • title – the text you want to appear on the title bar. • messageType – indicates the nature of the message box. It is of the int type but you don’t have to enter an integer. Instead, you may enter one of the following easy-to-read words and Java will translate it into an integer for you. • JOptionPane.INFORMATION_MESSAGE: Standard info icon is used. • JOptionPane.PLAIN_MESSAGE: No icon is displayed. • JOptionPane.QUESTION_MESSAGE: Question mark icon is displayed. • JOptionPane.WARNING_MESSAGE: Warning icon is displayed.
Input Dialog box • Displays a displays a text field into which the user can enter a string. • showInputDialog(Component parent, Object prompt, String title, intmesssageType) • parent – use null for projects • prompt – the prompt you want to display. A string is fine as it’s an object. • title – the text you want to appear on the title bar. • messageType – indicates the nature of the message box. The options are: • JOptionPane.ERROR_MESSAGE • JOptionPane.INFORMATION_MESSAGE • JOptionPane.PLAIN_MESSAGE • JOptionPane.QUESTION_MESSAGE • JOptionPane.WARNING_MESSAGE
Formatting Numeric Output • The DecimalFormat and NumberFormat classes allow you to specify the display format of numbers - number of digits, number of places after the decimal, formatting elements such as dollar signs and percent signs, etc. • Both classes are in the java.text package. • Importing is needed. • Usage pattern: • Create a formatting object (either a DecimalFormat or a NumberFormat object). • Call the format method of the formatting object and pass the number to be formatted as the argument. • A formatting object may be used to format multiple numbers. • If numbers are to be formatted in different ways, then multiple formatting objects are needed.
DecimalFormatClass Pattern characters: 0 required digit # optional digit, suppress if 0 . decimal point , comma separator % multiply by 100 and display a percent sign
The Wrapper Classes • There are occasions when you want to work with a number as an object. • Numbers are primitive types. They are not objects. • Wrapper classes resolve the problem because they are objects so can be handled as such. • In the “core” of each wrapper object is a numeric value.
Wrapper Classes • Remember the naming convention: • Primitive types start with a lowercase letter; Class names start with an uppercase letter.
Using Wrapper Classes • A handy use of wrapper class is a static method for converting textual input into numbers. • Usually, when a program obtains input from users, the input is read as strings. Even when the user enters a number, it’s still a string (of characters that stand for numbers). • Despite looking numeric ostensibly, such strings cannot be used in mathematic operations. They must be converted into primitive types first. • To perform the conversion, call the respective parseX() method of the wrapper class. • To convert a string into an integer, call parseInt(). • To convert a string into a double, call parseDouble().
Reading Numeric Input • The showInputDialog()method returns a string. • To convert the string to a numeric type, use the wrapper class methods. • Example: String input = JOptionPane.showInputDialog(null,"Please enter your age in years.", "Get Input", JOptionPane.QUESTION_MESSAGE); int age = Integer.parseInt(input);
MathClass • The Math class provides static constants and static methods for performing common calculations. • The Math class is in the java.lang package, so it does not need to be imported. • Methods in the Math class are static.
The round() Method • Rounding rules: • Any factional part < .5 is rounded down • Any fractional part .5 and above is rounded up
The min() and max()Methods Find smallest of three numbers: int smaller = Math.min( num1, num2 ); int smallest = Math.min( smaller, num3 );
Instance Variable • Instance variables are used to store data specific to a particular object. • An instance variable doesn’t exist (no memory location is assigned to it) until an object of that class is created. • All objects of the same class have the same instance variables. • However, for each object, the variables store values that are unique to that object. • Example: • The Student class has an instance variable called untId. • alice and bob are two instances of the Student class. • In the alice object, the untId variable contains the value 10101111. • In the bob object, the untId variable contains the value 10102222.
Static Variable • A class may also contain static variables. • Once a static variable is defined in the class, it comes into being immediately. No instantiation is needed. • Static variables can be accessed from outside of the class by following the ClassName.staticVarName syntax. • Values stored in static variables are not tied to any particular instances of the class. Rather, they are relevant at the class level. • Example: • The Student class has a studentCount static variable. • The number of all Student objects ever created can be stored in the studentCount variable. • It is not related to any particular Studentobject. If it were, we could have a “the-chicken-or-the-egg” problem.
Instance Method • Instance methods are used to define actions that an object of the class is capable of performing. • An instance method cannot be called until an object of that class is created. • An instance method is defined the same way for objects of the same class. However, even if the action is the same, in each object, the action works on data unique to that object(stored in the respective instance variables). • Example: • The Student class has an instance method called showStudentId(). • alice and bob are two instances of the Student class. • When called on the alice object, the showStudentId()method displays the value 10101111. • When called on the bob object, the showStudentId()method displays the value 10102222.
Static Method • A class may also contain static methods. • Once a static method is defined in the class, it comes into being immediately. No instantiation is needed. • Static methods can be accessed from outside of the class by following the ClassName.staticMethod() syntax. • It can be used to perform action that is relevant to all instances of the class. • Example: • The Student class has an addToCount()static method and a getStudentCount()static method. • The addToCount()method increments the student count whenever a new student object is instantiated. • The getStudentCount()method displays the current count of student objects.
Encapsulation • A fundamental concept in OOP. • The values of instance variables inside a class shouldn’t be changed arbitrarily by other classes. • They should be declared as “private”. • Manipulation of their values are done only by special-purpose methods inside the class. • These methods are public and “exposed”. • Setting values is possible only through calling these methods. • If program logic requires that these values to be changed, regardless of where the program execution is done, these special-purpose methods must be called.
Encapsulation • For example, suppose the main method is inside the Driver class and it needs to set the value of studentID of a Student object called alice, • It shouldn’t do: alice.studentID = "12345"; • Instead, the setter method of that property should be run: alice.setStudentID("12345"); • Whether a field or method is accessible (visible) to other classes is controlled by access modifiers. • public (UML sign + ) – All other classes can access the member. • private (UML sign - ) – Other classes must access the member through special methods defined in this class.
UML Representation of a Class + public - private
Access Modifiers * Through inheritance
Storing Values to Instance Variables • Constructor Methods • A constructor is a special method that is run when an object is created. It is typically used to set initial (default) values for instance variables. • A class may have more than one constructor, i.e., constructors often are overloaded. • Setter (mutator) Methods • A setter method is a void method that performs an action (set the value of an instance variable). • It takes a parameter – the value to be stored in the variable. • It does not return a value.
Accessing Values of Instance Variables • Getter (Accessor) Methods • A setter method is a value-returning method that returns a value (the value of an instance variable). • It does not have parameters.
Constructor • When an object is instantiated, the instantiation process runs the class’ constructor method. • If the business rules of your application require other initial values for (some of all) variables in your class, then you need to write a constructor and assign initial values to those that need them. • A constructor may also perform some initial actions in addition to or instead of setting initial values for variables. • Besides initializing instance variables, a constructor may also work with static variables/methods of the class. • A constructor must use the same name and capitalization as the name of the class.
Default Initial Values • If you haven’t defined a constructor for the class, Java will create a default constructor for you
Overloaded Constructor • Often, even though objects are instantiated from the same class, you want their variables to be initialized differently or different sets of variables to be initialized. • To achieve that, you write a few different constructors accordingly. • Constructors often are overloaded.
Setter Method • The program logic may need to change the value of an instance variable after it is initialized by the constructor. To do that, the setter method of that variable needs to be called. • The design pattern of a setter: • Access modifier: public • Return value: void • Naming: setVarName • Parameter list: one and only one parameter – (dataTypeparamName) • Method body: although more complicated assignment may be needed sometimes, typically the method contains only one assignment statement that assigns the parameter value to the variable – varName = paramName;
Getter Method • A getter method retrieves the value of an instance variable on behalf of methods in external classes. • The design pattern of a getter: • Access modifier: public • Return value: <dataTypeOfVar> • Naming: getVarName • Parameter list: () • Method body: although more complicated actions may be needed sometimes, typically the method contains only one statement that returns the value of the variable – return varName;
Access Method Examples • Example: // Declare the property private double unitPrice; … // The setter method public void setUnitPrice (double price) { unitPrice = price; } // The getter method public double getUnitPrice { return unitPrice; }
The this Keyword • If inside a constructor or setter method, the parameter name is the same as the name of the instance variable that will be assigned the parameter’s value, there should be a way to differentiate the “namesakes.” • The this keyword is used to refer to the object itself. • Variable name preceded by this and a dot refers to the instance variable itself. • Variable name standing by itself refers to the parameter. public void setUnitPrice (double unitPrice) { this.unitPrice = unitPrice; }