0% found this document useful (0 votes)
92 views10 pages

Chapter 3 PDF

The document discusses the basic concepts of classes in Java, including: 1. Classes group data and methods together to represent objects, and objects are instantiated from classes using the new operator. 2. A class defines the blueprint for an object and includes data members and methods. 3. Common types of methods in a class include constructors, mutators, accessors, processors, printers, and toString methods. Constructors initialize objects, mutators set data, and accessors retrieve data.

Uploaded by

2022461692
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
92 views10 pages

Chapter 3 PDF

The document discusses the basic concepts of classes in Java, including: 1. Classes group data and methods together to represent objects, and objects are instantiated from classes using the new operator. 2. A class defines the blueprint for an object and includes data members and methods. 3. Common types of methods in a class include constructors, mutators, accessors, processors, printers, and toString methods. Constructors initialize objects, mutators set data, and accessors retrieve data.

Uploaded by

2022461692
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

CHAPTER 3

BASIC CONCEPTS OF CLASSES - PART 1

Class concept:
 Object is a variable. Class is a type of data. We declared class BUT manipulate objects
 Used to group data and function/method
 Object combines data and the operation on data in a single unit
 A collection of a fixed number of components called member

Constructing a class (programmer-defined classes)


 When a Java application is run, objects are created and their methods are invoked (are run).
 To create an object, there needs to be a description of it.
 A class is a description of a kind of object. A programmer may define a class using Java, or
may use predefined classes that come in class libraries
 A class is merely a plan for a possible object. It does not by itself create any objects.
 When a programmer wants to create an object the keyword new operator is used with the
name of the class. Creating an object is called instantiation.
 Constructed 2 parts :
- a declaration section, which contains the class names as well as variables (attributes)
and function prototypes
- an implementation section, which contains the function themselves (tasks)

Template for Class Definition

Import Statements

Class Comment

class { Class Name


class {

Data Members

Methods
(incl. Constructor)

}
}
Data members
 Can be private, public, protected as modifier
 private (means data locally used within the class only) usually for declaring variables
for example:

private int num1, num2;

 public (means these methods can be called within class and also in main class)
usually as method definition for example:

public int area()


{ return width*length; }

 Protected referred to data members that strictly can be accessed by its super class and
subclass (inheritance) for example:

protected String name;

Basic types of methods:


1. Constructor
2. Mutator
3. Accessor/Retriever
4. Processor
5. Printer
6. toString() method (also type of printing method)

1. Constructor
 A member function that is used to initialized the object.
 Same name as the class name.
 Does not associate with any return type and void.
 It will be invoked automatically each time an object of the class is created (instantiated).
 It can be overloaded to provide a variety of means for initializing objects of a class.
 Always define a constructor and initialize data members fully in the constructor so an
object will be created in a valid state

Declaring a constructor
A constructor is written similar to a function, but with the following differences:
 No return type
 No return statement

Three types of constructor: default, normal and copy constructor


Default constructor
 A constructor takes no arguments
 The object is still guaranteed to be initialized to a constant state due to default argument.
 For example a class named Rectangle has been defined:
//default constructor
public Rectangle ()
{ width = 0.0;
length = 0.0;
}
Normal Constructor
 Used to override default arguments set in default constructor
 Data members in the created object will set by the value sent through its parameters
 For example based on class named Rectangle:
//default constructor
public Rectangle (double w, double l)
{ width = w;
length = l;
}

Copy constructor
 Allow one object to copy the value of another object’s data members.
 For example:
public Rectangle (Rectangle rect)
{ width = rect.width;
length = rect.length;
}

2. Mutator (setter)
 A Mutator - Sets a property (data, attribute) of an object. Usually the word set is being
used.
• Example: - setkan data
- setkan as private (kelas lain x bole kacau)
a) void setData (int w, int l)
{ width = w;
length = l; }
b) void setLength(int l )
{ length = l; }
c) void setWidth(int w)
{ width = w; }
3. Accessor / retriever (getter)
• Return information about an object - mesti public (kelas lain bole pkai)
• Example:
//returns the length of a //rectangle
public double getLength( )
{ return length; }
• getLength()– return information about the length of a rectangle

4. Processor
 A function used to perform calculation / operation to update specific data members or
might return a specific value.
• For example to calculate the area of a rectangle:
public double calculateArea()
{ return (width * length); }

5. Printer
 A function used to display information of a class. Usually the word display or print
had being used.
• For example to display all information about the object of a rectangle:
- nk print
- print class info (attribute(name, ic, address))
public void displayArea()
{
System.out.println(“Width “ + getWidth());
System.out.println(“Length “ + getLength());
System.out.println(“The area is “ + calculateArea();
}

6. toString()
 Method that returns a string representation of an object.
• For example a rectangle:
public String toString() - kena set public
{ - result masuk dlm println
return “Width “+ getWidth() +”\n” - + “Length “ + getLength()
+ “\n” + “The area is “ + calculateArea();
}

Example of program 1: (refer to Wu page 153)

class Bicycle {
// Data Member
private String ownerName;

//Constructor: Initializes the data member


public Bicycle( ) {
ownerName = "Unknown";
}

//Returns the name of this bicycle's owner


public String getOwnerName( ) {
return ownerName;
}

//Assigns the name of this bicycle's owner


public void setOwnerName(String name) {
ownerName = name;
}
}
Example of main / application program: (refer to Wu page 152)

class BicycleApp {
public static void main(String[] args) {

Bicycle bike1, bike2;


String owner1, owner2;
bike1 = new Bicycle( ); //Create and assign values to bike1
bike1.setOwnerName("Adam Smith");
bike2 = new Bicycle( ); //Create and assign values to bike2
bike2.setOwnerName("Ben Jones");

owner1 = bike1.getOwnerName( ); //Output the information


owner2 = bike2.getOwnerName( );
System.out.println(owner1 + " owns a bicycle.");
System.out.println(owner2 + " also owns a bicycle.");
}
}

Example 2 class Students:

class Students
{
private String name; // Data Members
private long id;

// Default Constructor
public Students()
{
name = "Unassigned";
id = 0;
}

//Accessor: Returns the name of this student


public String getName( ) { return name;}

//Accessor: Returns the id of this student


public long getId( ) { return id;}

//Mutator: Assigns the name and id of this student


public void setData(String studentName, long studId)
{ name = studentName;
id = studId; }

// display all information using toString() method


// return the string representation of the object
public String toString()
{ return "Name: " + name + "\n" + “Student id: " + id;}
}

Class StuApp
/*
Purpose: This programs tests the class Students
*/
import java.util.*;
public class StuApp
{
public static void main( String[] args )
{
Scanner in = new Scanner(System.in);
Students stu1; // declare an object reference
stu1 = new Students( ); //create an object of type Students
System.out.println(" Enter name "); //input name
String nm = in.next();
System.out.println(" Enter id");// input id
long id = in.nextLong();
stu1.setData(nm,id); // set data through mutator
System.out.println(" The student's name:” +
stu1.getName()));
System.out.println(" The student's id: " + stu1.getId( ));
System.out.println(stu1.toString( ));
}// end main
}// end class

Method Definition

Method Declaration

<modifier> <return type> <method name> ( <parameters> ){


<statements>
}

Modifier Return Type Method Name Parameter

public void setOwnerName ( String name ) {

ownerName = name; Statements

• public : makes the classes, data or methods are accessible from any class
• private : makes the data or methods are accessible ONLY within its own class

Data members should be private


members are the implementation details of the class, so they should be invisible to the
clients. Declare them private.

Constants can (should) be declared public if they are meant to be used directly by
the outside methods

Local variables
variables are declared within a method declaration and used for temporary services,
such as storing intermediate computation results.
public double convert(int num)
{
double result; //local variable
result = Math.sqrt(num * num);
return result;
}
Local, parameter & data member

member.

al variable declaration or a parameter, then the identifier refers to the


local variable or the parameter.

member.
no matching declaration.

A static method
 Class method that does not operate on an object
 Defined inside a class
 Can be called preceded by the class name
 No object need to be created to call it

Syntax:
className.methodName(parameters)

Examples:
a) public static void main(String args[])
b) Math.sqrt(16);

Note:
 Math is a class, not an object
 sqrt()is a static method in Math class.

A static field
 A class constant that is shared by all methods of the class.
 One copy per class is shared by all objects.
 Constant should be made final static.
 Example:
private static final float pi = 3.142;

Predefined classes and wrapper classes


 Predefined classes that already defined in java application package
 Wrapper classes – will process primitive data type values as object eg wrapping int into
Integer class and wrapping double into the Double class
 For example (page 111) to convert “14” to 14:
int num = Integer.parseInt(“14”); - berkaitan no
int num = Integer.parseInt(scan.next()); -selalunya ic no : string/int
- string (ic) nk dptkan no negeri
int num = scan.nextInt();
Wrapper class in java provides the mechanism to convert primitive into object and object
into primitive.

Since J2SE 5.0, autoboxing and unboxing feature converts primitive into object and object
into primitive automatically. The automatic conversion of primitive into object is known and
autoboxing and vice-versa unboxing.

One of the eight classes of java.lang package are known as wrapper class in java. The list of
eight wrapper classes are given below:

Primitive Type Wrapper class


boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double

Wrapper class Example: Primitive to Wrapper


copy to clipboard
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally

System.out.println(a+" "+i+" "+j);


}
}

public class WrapperExample1{


public static void main(String arg
//Converting int into Integer
int a=20;

Output:
20 20 20

Source: http://www.javatpoint.com/wrapper-class-in-java
Example of program using static method

public class Customer


{
private String customerID;
private String customerName;
private String address;
private int pinCode;
private static int count;

//Description: Blank Constructor


public Customer() {
count++;
}

//return Returns the address.


public String getAddress() {
return address;
}

//parameter address The address to set.


public void setAddress(String address) {
this.address = address;
}

//return Returns the customerID.


public String getCustomerID() {
return customerID;
}

//parameter customerID The customerID to set.


public void setCustomerID(String customerID) {
this.customerID = customerID;
}

//return Returns the customerName.


public String getCustomerName() {
return customerName;
}

//parameter customerName The customerName to set.


public void setCustomerName(String customerName) {
this.customerName = customerName;
}

//return Returns the pinCode.


public int getPinCode() {
return pinCode;
}
//parameter pinCode The pinCode to set.
public void setPinCode(int pinCode) {
this.pinCode = pinCode;
}

//return Returns the count.


public static int getCount() {
return count;
}
}

//This java file is a Demo Java program which depicts StaticDemo


//class.
//This class is demo class to illustrate the concept of static data
public class StaticDemo {
public static void main(String[] args) {
System.out.println("No. of customer objects initially: "+
Customer.getCount());
Customer customer1 = new Customer();
Customer customer2 = new Customer();

System.out.println("No. of customer objects currently: "+


Customer.getCount()); //called static method
}
}

You might also like