B asic Concepts of Classes

37
Basic Concepts of Classes Chapter 3

description

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. - PowerPoint PPT Presentation

Transcript of B asic Concepts of Classes

Page 1: B asic Concepts of Classes

Basic Concepts of Classes

Chapter 3

Page 2: B asic Concepts of Classes

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

Page 3: B asic Concepts of Classes

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 Concept

Page 4: B asic Concepts of Classes

Class_name

instance_variables

methods

Class Diagram

Page 5: B asic Concepts of Classes

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 variablestype var1;type var2;

  //declare methodstype 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

Page 6: B asic Concepts of Classes

Class Defination

Defining Classes:

The syntax:

<modifier> class <Classname> {//body of class

}

Example:public class Student {

//body of class}

Page 7: B asic Concepts of Classes

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

Page 8: B asic Concepts of Classes

Access Modifier / Access Specifier

Data (data members) are usually declared as private While the behaviors of the instances is implemented by public

methods

VISIBILITY public protected private

From the same class YES YES YES From any class in the same package YES YES NO From any class outside the package YES NO NO From a subclass in the same package YES YES NO From a subclass outside the package YES YES NO

Page 9: B asic Concepts of Classes

Defining a Class

General syntax:

<modifier> class <Classname> {

…… //body of class}

first letter is uppercase

public modifier is commonly used

Page 10: B asic Concepts of Classes

Instance variables Syntax:

<modifier> <primitive/reference data type><variable> ;

Class variables Syntax:<modifier> static <primitive data type/reference data type><variable> ;

private modifier is used

Variables

Page 11: B asic Concepts of Classes

General syntax :

<modifier> <returntype> <nameOfMethod>( parameter){

…… //body of class}

public modifier is commonly used

The identifier starts with a lowercase letter

Primitive/reference

Methods

Page 12: B asic Concepts of Classes

Common Methods in a Class

•Has the same identifier as the class•A method that is automatically executed when an object is created.•Two types :•Default :constructor that accepts no arguments and has no statements in its

body.•Normal : with or without arguments and has statements in its body

Constructor

•A method that modifies one or more data members.Mutator/Set

•A method that only access a data member.Accessor / Get

•To perform other than modifying data members. •Normally use to do calculation

Processor

•A method that display all the data members.•OR to return all the data members as string values

Printer

Page 13: B asic Concepts of Classes

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

Page 14: B asic Concepts of Classes

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 rectangleTherefore, Rectangle is suitable to be a class.

Page 15: B asic Concepts of Classes

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

Page 16: B asic Concepts of Classes

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 calculate and print the perimeter and area of the rectangle”

Page 17: B asic Concepts of Classes

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

Page 18: B asic Concepts of Classes

Example 1: continue..

Other operations that are customary to include: Get the Length Get the Width

Page 19: B asic Concepts of Classes

Example 1: continue..

RectanglelengthwidthsetLength()setWidth()getLength()getWidth()calculatePerimeter()calculateArea()print()Class

Diagram

Page 20: B asic Concepts of Classes

Example 1: Defining a Class and Variables

public class Rectangle{

private double length;private double width;

}

Page 21: B asic Concepts of Classes

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

Page 22: B asic Concepts of Classes

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

Page 23: B asic Concepts of Classes

Example 1: Accessor methods

//continue..

public double getLength(){

return length;}public double getWidth(){

return width;}

return value length

return value width

Page 24: B asic Concepts of Classes

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

Page 25: B asic Concepts of Classes

Example : Printer method

//continue..

public String toString(){

String out= “Length = “ + length + “\nWidth = “ + width;

return out;}

Return all values as String

Page 26: B asic Concepts of Classes

java

lang

String

(package)

(subpackage)

Methods-insert()-reverse()-charAt()-length()-ext

Methods-chatAt()-length()-indexOf()-equals()-toString()-ext

(class)

Math

Methods-Math.sqrt()-Math.min()-ext

(class)

(class)

StringBuffer

Page 27: B asic Concepts of Classes

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

Page 28: B asic Concepts of Classes

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

Page 29: B asic Concepts of Classes

Predefined classes Example: Math Class

Page 30: B asic Concepts of Classes

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]}

Page 31: B asic Concepts of Classes

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.

Page 32: B asic Concepts of Classes

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

Page 33: B asic Concepts of Classes

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

Page 34: B asic Concepts of Classes

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

Page 35: B asic Concepts of Classes

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.

Page 36: B asic Concepts of Classes

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).

Page 37: B asic Concepts of Classes

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.