0% found this document useful (0 votes)
6 views39 pages

Topic 3 - Basic Classes

The document provides an overview of basic classes in Object-Oriented Programming (OOP) with a focus on Java. It covers class concepts, data members, methods, constructors, and predefined classes, emphasizing the structure and functionality of user-defined classes. Additionally, it explains modifiers, static fields, and wrapper classes, along with examples and syntax for better understanding.

Uploaded by

sazuntemavira
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)
6 views39 pages

Topic 3 - Basic Classes

The document provides an overview of basic classes in Object-Oriented Programming (OOP) with a focus on Java. It covers class concepts, data members, methods, constructors, and predefined classes, emphasizing the structure and functionality of user-defined classes. Additionally, it explains modifiers, static fields, and wrapper classes, along with examples and syntax for better understanding.

Uploaded by

sazuntemavira
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/ 39

Topic 3:

Basic Classes

CSC435: OBJECT ORIENTED PROGRAMMING

Prepared by Siti Norsyuhada Zainudin


Content

Class concept & definition

Data members

Basic types of methods

Methods definition

Static fields

Predefined classes and wrapper classes


Class Concept &
Definition
Class Concept

 In OOP, the central modules are classes where data and the procedure to manipulate the data are
encapsulated
 A Java program is composed of one or more classes.
 One of the classes in a program must be designated as the main class
 To design a class, you must know what data need to manipulate and what operations need to
manipulate the data
Class Definition

 Classes we define ourselves are called


programmer/user-defined classes.
 Every object is an instance of a class.
 A class is a type or category of objects
(object definition)
 A class provides blueprint (structure) for its
objects
 A class definition contains
 Data member (usually specified as
private modifier)
 Methods (usually specified as public
modifier)
Class Definition - Template
Class Definition: Syntax

Class header

modifier class className


Modifier (s)
• Used to alter the { classMembers
• Consists of named
behavior of the class classMembers constants, variable
• type of modifiers
declarations, methods,
(public, private and }
other classes
static)
Data Members
Data Members

 The components of a class are called members of the class


 Data members is the object attributes – also known as attributes,
fields, variables, or properties
 Members can be variables (data) or methods
 Data members can be any data type:
 primitive or
 object (class)
Data Member-Syntax

<modifier> <data type> <name>

private String name;


private int ID;
Private double balance;
Modifier

 Modifier is used to control access to data, methods and classes.


 It restricts who can have a direct access to the data member

Private Public Protected Default

• Data locally • Methods can be • Referred to data • Can be


used within the called within members that accessed by
class only class and also in strictly can be any class in the
• Usually for main class accessed by its same package
declaring • Usually as super class and
variables method subclass
definition
Example Class with Data Members & Modifiers
Basic Types of Methods
& Method Definition

Accessor /
Constructor Mutator
Retriever

Processor Printer toString()


Constructor

Special method that is executed automatically when a


new instance of the class (object) is created

 Features:  Types of constructor:


 Same name as the class name  Default constructor
 Does not associate with any  Normal constructor
return type and void  Copy constructor
 It may have parameter
Constructor : Default Constructor

Public class Student()


 A constructor takes no arguments {

 Automatically created by Java if private String name;


you don’t define a constructor for
a class public Student()
 The object is still guaranteed to be {
initialized to a constant state due name=“ ”;
to default argument. }
}
Constructor : Normal Constructor

Public class Student()


 Receives several values from the {
main method through parameters private String name;
 Used to override default arguments private int age;
set in default constructor
public Student(String nm, int umur)
 Initialize the data members of an
{
object with the given value.
name = nm;
 Can be overloaded as long as the age = umur;
number of parameters and/or the }
type of parameters are different }
Constructor : Copy Constructor

 A constructor that initializes a new Public class Student()


object by using the values of an {
existing object private String name;
 It is used to copy an object into
another object
public Student(Student nm)
 The parameter of a copy constructor
{
is an object from the same class
name=nm.name;
 Copy constructor makes a member-
by-member copy from the argument }
to the object being created }
Constructor : Copy Constructor

Public class Student() Public class Student()


{ {
private String name; private String name;

public Student(Student nm) OR public Student(String name)


{ {
name=nm.name; this.name=name;
} }
} }
Mutator (setter)

 Is to change one or more of an object’s values after the object is


created and initialized
 It does not return any value, void method.
 Has arguments (parameter list) to set the variables

Public class Student


{
public void set<variable>(<dataType> String name;
<newValue>) { public void setName(String name)
this.<variable> = <newValue>; {
} this.name = name;
}
}
Accessor (getter)

public class Person


{
private String name;
private int age;
 Used to read / access the values
public String getName()
stored in object’s variables {
 Returns a value read return name;
}
 No arguments (parameter list)
public int getAge()
{
return age;
}}
Processor

 A function used to perform calculation / operation to update specific


data members or might return a specific value.

public double calculateArea()


public double calculateArea() {
{ OR double area;
return (width * length); area = width * length;
} return area;
}
Printer

 Used to display the values stored in object


 Usually the word display or print had being used.
 For example to display all information about the object of a
rectangle:

public void displayArea()


{
System.out.println(“Width “ + getWidth());
System.out.println(“Length “ + getLength());
System.out.println(“The area is “ + calculateArea();
}
toString()

 Method that returns a string representation of an object.

public String toString()


{
return “Width “+ getWidth() +”\n” + “Length “ + getLength() + “\n” +
“The area is “ + calculateArea();
}
Static Fields
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

public static void main(String[] args) {…..}


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.

private static final float pi = 3.142;


Predefined Classes
and Wrapper Classes
Predefined Classes

 Java compiler automatically imports all the classes in the java.lang


package into every source file.
 Some of the most important classes of the java.lang package

String
StringBuffer
Math
Vector
Hashtable
Predefined Classes

Predefined method Usage Example


substring() To extracet a few characters from a string String a=name.substring(i,j);
length() To return total number of characters in a Int nume = name.length();
string
indexOf() To return index of specified first character JAVA
name.indexOf(“J”);
charAt() To get individual character based on name=“Syuhada”
index given as parameter char x = name.charAt(5);
Equals() To determine two String objects contain Boolean b = name.equals(name1);
exactly the same data. It return true or
false
equalsIgnoreCase To determine two String objects contain Boolean b =
the same data regardless of upper case name.equalsIgnoreCase(name1);
or lower case. It return true or false
Wrapper Classes

 Process primitive data type values as object


Primitive Data Type Wrapper Class Method
Int Integer Integer.parseInt()
Float Float Float.parseFloat()
Double Double Double.parseDouble()
Byte Byte Byte.parseByte()
Short Short Short.parseShort()
Long Long Long.parseLong()
Char Character Character.parseChar()
Boolean Boolean Boolean.parseBoolean()
Wrapper Classes – Example (pg 111)

Instead of using the data type specific methods such as nextInt, nextDouble, and
others of the Scanner class, we can input a numerical value in a string format and
convert it to an appropriate data type by ourselves. For example, we can use the
class method parseInt of the Integer class to convert a string to an int. Here’s a
statement that converts "14" to an int value 14:
int num = Integer.parseInt("14");
So, the statement
int num = Integer.parseInt(scanner.next( ));
is equivalent to
int num = scanner.nextInt( );
Sample Program
public class Actor Class header : modifier, reserved word class and class name
{
private String actName;
Attributes / data members/ variables
private String movieName; declaration: identify attributes of an object
private double hourWork; and its data type

Default constructor : initialize the object


public Actor() variables to zero or null
{
actName =“”;
movieName = “”;
hourWork = 0.0;
}

public void setData(String n, String m, double h) Mutator method : to set the object’s value

Method definition {
actName = n;
movieName = m;
hourWork = h; }

public String toString() I/O method : to display the object’s values


{
return ( actName + “ “ + movieName + “ “ + hourWork ) ;
}
}
import java.util.*; Import the package : be able to use the pre-defined
classes

public class ActorApp Class header : modifier, reserved word class and class name
{
public static void main(String[] args) Main method
{
Create input object : to input
Scanner a = new Scanner(System.in); using I/O console

To create Actor’s object Actor x = new Actor();

System.out.println("Enter actor's name: ");


String name = a.next();

System.out.println("Enter actor's movie : "); Read the input


String movie = a.next(); entered by user using
I/O console
System.out.println("Enter hour work ");
double hour = a.nextDouble();

To set the object’s values


x.setData(name, movie, hour);
(properties values)

To display the object’s values System.out.println(x.toString ());


}
}

You might also like