370 likes | 553 Views
B asic Concepts of Classes. Chapter 3. Chapter 3. 3.0 Basic Concepts of Classes 3.1 Class Concept 3.2 Class Defination 3.3 Data Members 3.4 Basic Types of Methods 3.5 Methods Defination 3.6 Static Fields 3.7 Predefined classes and wrapper classes. Class Concept.
E N D
Basic Concepts of Classes Chapter 3
Chapter 3 • 3.0 Basic Concepts of Classes • 3.1 Class Concept • 3.2 Class Defination • 3.3 Data Members • 3.4 Basic Types of Methods • 3.5 Methods Defination • 3.6 Static Fields • 3.7 Predefined classes and wrapper classes
Class Concept • The class is at the core of Java. Any concept you wish to implement in a Java program must be encapsulated within a class. • Object-oriented program consists of at least one class. A class consists of variables/data and methods. • Running an OO program requires a main method. If there are more than one class, there should be a(an) main/application class which includes the main method. • You will learn the basic elements of a class and how to create objects from the class.
Class Defination General Form of a Class: A class is consists of data and code that operates on that data. The following is a general form of a class. class Classname { //declare instance variables type var1; type var2; //declare methods type method1(parameters){ //body of method } //end of method1 type method2(parameters){ //body of method } //end of method2 } //end of class Class declaration Variables declaration Methods
Class Defination Defining Classes: The syntax: <modifier> class <Classname> { //body of class } Example: public class Student { //body of class }
Access Modifier / Access Specifier • Encapsulation links data with the code (methods/operations) that manipulates it. • Through encapsulation, you can control what parts of a program can access the members of a class. It is to prevent misuse. • How a member of a class can be accessed is determined by the access modifier that modifies its declaration. • Java’s access modifiers are: • public • private • protected
Access Modifier / Access Specifier • Data (data members) are usually declared asprivate • While the behaviors of the instances is implemented by public methods
Defining a Class General syntax: <modifier> class <Classname> { …… //body of class } publicmodifier is commonly used first letter is uppercase
Variables privatemodifier is used • Instance variables • Syntax: <modifier> <primitive/reference data type><variable> ; • Class variables • Syntax: <modifier> static<primitive data type/reference data type><variable> ;
Methods public modifier is commonly used • General syntax : <modifier> <returntype> <nameOfMethod>( parameter) { …… //body of class } Primitive/reference The identifier starts with a lowercase letter
Example 1: Q: Write a program to input the length and width of a rectangle and calculate and print the perimeter and area of the rectangle. Step 1 : Identify all the relevant nouns. • Length • Width • Rectangle • Perimeter • Area
Example 1: continue… Step 2 : Identify the class(es). It is clear that: • Length – length for the rectangle • Width – width for the rectangle • Rectangle • Perimeter – perimeter for the rectangle • Area – area for the rectangle Therefore, Rectangle is suitable to be a class.
Example 1: continue.. Step 3 : Identify the data members for each of the classes. Determine the information that is essential to describe each class. • Perimeter – is not needed. It can be computed from length & width. • Area – is also not needed. It can be computed from length & width. • Length – is required . It is one of the data member • Width – is required. It is one of the data member
Example 1: continue.. Step 4 : Identify the operations for each of the classes. The operations can be determine by looking at the verbs. For example: input, calculate & print “Write a program to input the length and width of a rectangle and calculateand print the perimeter and area of the rectangle”
Example 1: continue.. Therefore, you need at least the following operations. • Set the Length • Set the Width • Calculate the Perimeter • Calculate the Area • Print the perimeter • Print the area
Example 1: continue.. Other operations that are customary to include: • Get the Length • Get the Width
Example 1: continue.. Class Diagram
Example 1: Defining a Class and Variables publicclass Rectangle { private double length; private double width; }
Example 1: Constructor public class Rectangle { private double length; private double width; public Rectangle ( ) { length=0.0; width=0.0; } } Set initial values for all variables
Example 1: Mutator methods //continue.. public void setLength( double len) { length=len; } public void setWidth(double wid) { width=wid; } Assign value len to length Assign value wid to width
Example 1: Accessor methods //continue.. public double getLength() { return length; } public double getWidth() { return width; } return value length return value width
Example 1: Processor methods //continue.. public double calculatePerimeter() { double perimeter=(2*length)+2*width; return perimeter; } public double calculateArea() { return length*width; } Calculate & return value perimeter Calculate & return value area
Example : Printer method //continue.. public String toString() { String out= “Length = “ + length + “\nWidth = “ + width; return out; } Return all values as String
Methods -Math.sqrt() -Math.min() -ext java (package) lang (subpackage) (class) Math Methods -chatAt() -length() -indexOf() -equals() -toString() -ext (class) String (class) StringBuffer Methods -insert() -reverse() -charAt() -length() -ext
Predefined classes System.in • provides only a facility to input 1 byte at a time with its read method • need an input facility to process multiple bytes as a single unit. • *associate a Scanner object to the System.in object. Scanner • Scanner object will allow us to read primitive data type values and strings. • Located in java.util.*. *other methods : nextByte(), nextDouble(), nextFloat(), nextLong(), nextShort(), next() – for String values
Predefined classes Math(refer Java API documentation) • contain class methods for commonly used mathematical functions • to call these class methods, you can use the following syntax: Math.<method()> • among others: • sqrt (a) – returns square root • min (a,b) – returns the smaller of a and b • max(a,b) – returns the larger of a and b • example : double punca= Math.sqrt(25); http://www.leepoint.net/notes-java/summaries/summary-math.html
Predefined classes Example: Math Class
Wrapper • Java wrappers are classes that wrap up primitive values in classes that offer utility methods to manipulate the values. • Utility class that has useful methods to be performs on primitive data. • One of the method is to perform type conversion. • Example: • parseDouble() method from Double class • parseInt() method from Integer class {Lab 2 Java Programming Basic[IOconsoleExample]}
Wrapper String • A string is a sequence of characters that is treated as a single value. • As stated earlier, String is part of java.lang package which is automatically included during compilation. • About 50 methods defined in the String class. Some of the predefined methods of String class that commonly used are : • substring( a, b ){Tutorial 2[Q2]} • a – specifies the position of the 1st character • b – specifies the value that is 1 more than the position of the last character. • this method returns a substring from a to (b-1) index of a string object.
Wrapper • length(){Tutorial 2[Q2]} • returns the number of characters of a sting. • indexOf(){Note 02 Example[Example 3]} • to locate the index of a substring within another string. • returns the index. • charAt(n) {Tutorial 2[Q2]} • to access an individual character of a string. n is the index /position of that character in a string. • toUpperCase(){Tutorial 2[Q2]} • converts every character in a string to uppercase
Wrapper • equals(){Tutorial 3[Worker]} • use to compare two string objects and returns TRUE if the two objects have the exact same sequence of characters. • Example : str1.equals(str2) • Returns TRUE if str1 equals to str2 and FALSE if they’re not equal. • equalsIgnoreCase(){Tutorial 3[Worker]} • has the same function as the equals() method but the comparison is done in a case-insensitive manner. • Example: str1=”hello”; • str1.equalsIgnoreCase(“Hello”); ----returns TRUE
Wrapper • compareTo() • compare two string objects. • Example : str1.compareTo(str2) • Will returns 0 if they are equal, a negative integer if str1 is less than str2, and a positive integer if str1 is greater than str2
Wrapper toString() {Tutorial 3[Worker]} • Creates a string that is the name of object’s class • Is a public value-returning method. • Not take any parameters and returns the address of a String object • The heading: • public String toString() • Can override the default definition of the method toString() to convert an object to desired string. • Is useful for outputting the values of the instance variables.
Exercises on methods of string class Exercise 1: ReverseCharacter • Write a program which requests a line of String from user. Store the String characters to an array. Then displays the character in reverse order with all words print in uppercase. Exercise 2: Egg • Write a program which requests a line of String from user. Then displays each words in reverse order. Convert it to a new string by placing egg in front of every vowel (a, e, u).
Exercises on methods of string class Exercise 3: ReverseWord • Write a program which requests a line of String from user. Then displays each words in reverse order. Exercise 4: ReverseWorldLine • Write a program which requests a line of String from user. Then displays each words in separate lines and in reverse order.