SlideShare une entreprise Scribd logo
1  sur  32
1
User Defined Class
Syntax: Defining Class
 General syntax for defining a class is:
modifieropt class ClassIdentifier
{
classMembers:
data declarations
methods definitions
}
 Where
modifier(s) are used to alter the behavior
of the class
classMembers consist of data declarations
and/or methods definitions.
2
Class Definition
 A class can contain data declarations and method
declarations
3
int size, weight;
char category;
Data declarations
Method declarations
UML Design Specification
4
UML Class Diagram
Class Name
What data does it need?
What behaviors
will it perform?
Public
methods
Hidden
information
Instance variables -- memory locations
used for storing the information needed.
Methods -- blocks of code used to
perform a specific task.
Class Definition: An Example
 public class Rectangle
 {
// data declarations
 private double length;
 private double width;
 //methods definitions
 public Rectangle(double l, double w) // Constructor method
 {
 length = l;
 width = w;
 } // Rectangle constructor
 public double calculateArea()
 {
 return length * width;
 } // calculateArea
 } // Rectangle class
5
Method Definition
 Example
6
 The Method Header
modifieropt ResultType MethodName (Formal ParameterList )
public static void main (String argv[ ] )
public void deposit (double amount)
public double calculateArea ( )
public void MethodName() // Method Header
{ // Start of method body
} // End of method body
Method Header
 A method declaration begins with a method header
7
int add (int num1, int num2)
method
name
return
type
Formal parameter list
The parameter list specifies the type
and name of each parameter
The name of a parameter in the method
declaration is called a formal parameter
Method Body
 The method header is followed by the method body
8
int add (int num1, int num2)
{
int sum = num1 + num2;
return sum;
}
The return expression
must be consistent with
the return type
sum is local data
Local data are
created each time
the method is called,
and are destroyed
when it finishes
executing
User-Defined Methods
 Methods can return zero or one value
Value-returning methods
○ Methods that have a return type
Void methods
○ Methods that do not have a return type
9
calculateArea Method.
public double calculateArea()
{
double area;
area = length * width;
return area;
}
10
Return statement
 Value-returning method uses a return
statement to return its value; it passes a
value outside the method.
 Syntax:return statement
return expr;
 Where expr can be:
Variable, constant value or expression
11
User-Defined Methods
 Methods can have zero or >= 1
parameters
No parameters
○ Nothing inside bracket in method header
1 or more parameters
○ List the paramater/s inside bracket
12
Method Parameters
- as input/s to a method
public class Rectangle
{
. . .
public void setWidth(double w)
{
width = w;
}
public void setLength(double l)
{
length = l;
}
. . .
}
13
Syntax: Formal Parameter List
(dataType identifier, dataType identifier....)
14
Note: it can be one or more dataType
Eg.
setWidth( double w )
int add (int num1, int num2)
Creating Rectangle Instances
 Create, or instantiate, two instances of the Rectangle
class:
15
The objects (instances)
store actual values.
Rectangle rectangle1 = new Rectangle(30,10);
Rectangle rectangle2 = new Rectangle(25, 20);
Using Rectangle Instances
 We use a method call to ask each object
to tell us its area:
16
rectangle1 area 300
rectangle2 area 500Printed output:
System.out.println("rectangle1 area " + rectangle1.calculateArea());
System.out.println("rectangle2 area " + rectangle2.calculateArea());
References to
objects
Method calls
Syntax : Object Construction
 new ClassName(parameters);
Example:
 new Rectangle(30, 20);
 new Car("BMW 540ti", 2004);
Purpose:
 To construct a new object, initialize it with
the construction parameters, and return a
reference to the constructed object.
17
The RectangleUser Class
Definition
public class RectangleUser
{
public static void main(String argv[])
{
Rectangle rectangle1 = new Rectangle(30,10);
Rectangle rectangle2 = new Rectangle(25,20);
System.out.println("rectangle1 area " +
rectangle1.calculateArea());
System.out.println("rectangle2 area " +
rectangle2.calculateArea());
} // main()
} // RectangleUser
18
An application must
have a main() method
Object
Use
Object
Creation
Class
Definition
Method Call
 Syntax to call a method
methodName(actual parameter list);
Eg.
segi4.setWidth(20.5);
obj.add (25, count);
19
Formal vs Actual Parameters
 When a method is called, the actual parameters in the
invocation are copied into the formal parameters in
the method header
20
int add (int num1, int num2)
{
int sum = num1 + num2;
return sum;
}
total = obj.add(25, count);
 public class RectangleUser
 {
 public static void main(String argv[])
 {
 Rectangle rectangle1 = new Rectangle(30.0,10.0);

 System.out.println("rectangle1 area " +
 rectangle1.calculateArea());
rectangle1.setWidth(20.0);
 System.out.println("rectangle1 area " +
 rectangle1.calculateArea());
 }
 }
21
Formal vs Actual Parameters
Method Overloading
 In Java, within a class, several methods
can have the same name. We called
method overloading
 Two methods are said to have different
formal parameter lists:
If both methods have a different
number of formal parameters
If the number of formal
parameters is the same in both
methods, the data type of the
formal parameters in the order we
list must differ in at least one
position 22
Method Overloading
 Example:
public void methodABC()
public void methodABC(int x)
public void methodABC(int x, double
y)
public void methodABC(double x, int
y)
public void methodABC(char x, double
y)
public void methodABC(String x,int y)
23
Java code for overloading
 public class Exam
 {
 public static void main (String [] args)
 {
 int test1=75, test2=68, total_test1, total_test2;
 Exam midsem=new Exam();
 total_test1 = midsem.result(test1);
 System.out.println("Total test 1 : "+ total_test1);
 total_test2 = midsem.result(test1,test2);
 System.out.println("Total test 2 : "+ total_test2);
 }
 int result (int i)
 {
 return i++;
 }

 int result (int i, int j)
 {
 return ++i + j;
 }
 }
24
 Output
Total test 1 : 75
Total test 2 : 144
25
Constructors Revisited
 Properties of constructors:
Name of constructor same as the name of class
A constructor,even though it is a method, it has no
type
Constructors are automatically executed when a
class object is instantiated
A class can have more than one constructors –
“constructor overloading”
○ which constructor executes depends on the type of
value passed to the constructor when the object is
instantiated
26
Java code (constructor
overloading)
public class Student
{ String name;
int age;
Student(String n, int a)
{ name = n; age = a;
System.out.println ("Name1 :" + name);
System.out.println ("Age1 :" + age);
}
Student(String n)
{
name = n; age = 18;
System.out.println ("Name2 :" + name);
System.out.println ("Age2 :" + age);
}
public static void main (String args[])
{
Student myStudent1=new Student("Adam",22);
Student myStudent2=new Student("Adlin");
}
} 27
28
Output:
Name1 :Adam
Age1 :22
Name2 :Adlin
Age2 :18
Object Methods & Class
Methods
 Object/Instance methods belong to
objects and can only be applied after the
objects are created.
 They called by the following :
objectName.methodName();
 Class can have its own methods known
as class methods or static methods
29
Static Methods
 Java supports static methods as well as static variables.
 Static Method:-
 Belongs to class (NOT to objects created from the class)
 Can be called without creating an object/instance of the
class
 To define a static method, put the modifier static in the
method declaration:
 Static methods are called by :
ClassName.methodName();
30
Java Code (static method)
public class Fish
{
public static void main (String args[])
{
System.out.println ("Flower Horn");
Fish.colour();
}
static void colour ()
{
System.out.println ("Beautiful Colour");
}
}
31
32
Output:
Flower Horn
Beautiful Colour

Contenu connexe

Tendances

Applet and graphics programming
Applet and graphics programmingApplet and graphics programming
Applet and graphics programmingsrijavel
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword pptVinod Kumar
 
Namespace in C++ Programming Language
Namespace in C++ Programming LanguageNamespace in C++ Programming Language
Namespace in C++ Programming LanguageHimanshu Choudhary
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaTech_MX
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methodsShubham Dwivedi
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVASURIT DATTA
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstractionIntro C# Book
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsMayank Jain
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingKumar
 

Tendances (20)

Applet and graphics programming
Applet and graphics programmingApplet and graphics programming
Applet and graphics programming
 
Class 10
Class 10Class 10
Class 10
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
 
Namespace in C++ Programming Language
Namespace in C++ Programming LanguageNamespace in C++ Programming Language
Namespace in C++ Programming Language
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
Java arrays
Java arraysJava arrays
Java arrays
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
 

Similaire à Class & Object - User Defined Method

Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6sotlsoc
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Abou Bakr Ashraf
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.pptDeepVala5
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programmingRenas Rekany
 
Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Palak Sanghani
 
Chapter 6.5 new
Chapter 6.5 newChapter 6.5 new
Chapter 6.5 newsotlsoc
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0BG Java EE Course
 
Java căn bản - Chapter4
Java căn bản - Chapter4Java căn bản - Chapter4
Java căn bản - Chapter4Vince Vo
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IEduardo Bergavera
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsMuhammadTalha436
 
Chapter 6.5
Chapter 6.5Chapter 6.5
Chapter 6.5sotlsoc
 
Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Palak Sanghani
 
3 functions and class
3   functions and class3   functions and class
3 functions and classtrixiacruz
 
Csphtp1 06
Csphtp1 06Csphtp1 06
Csphtp1 06HUST
 

Similaire à Class & Object - User Defined Method (20)

Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6
 
Object and class
Object and classObject and class
Object and class
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
static methods
static methodsstatic methods
static methods
 
Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]
 
Chapter 6.5 new
Chapter 6.5 newChapter 6.5 new
Chapter 6.5 new
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
Java căn bản - Chapter4
Java căn bản - Chapter4Java căn bản - Chapter4
Java căn bản - Chapter4
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
Chapter 6.5
Chapter 6.5Chapter 6.5
Chapter 6.5
 
Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]
 
C# p8
C# p8C# p8
C# p8
 
Java class
Java classJava class
Java class
 
3 functions and class
3   functions and class3   functions and class
3 functions and class
 
Second chapter-java
Second chapter-javaSecond chapter-java
Second chapter-java
 
Csphtp1 06
Csphtp1 06Csphtp1 06
Csphtp1 06
 
Bc0037
Bc0037Bc0037
Bc0037
 

Plus de PRN USM

Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2PRN USM
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1PRN USM
 
File Input & Output
File Input & OutputFile Input & Output
File Input & OutputPRN USM
 
Exception Handling
Exception HandlingException Handling
Exception HandlingPRN USM
 
Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2PRN USM
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1PRN USM
 
Class & Object - Intro
Class & Object - IntroClass & Object - Intro
Class & Object - IntroPRN USM
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition StructurePRN USM
 
Selection Control Structures
Selection Control StructuresSelection Control Structures
Selection Control StructuresPRN USM
 
Numerical Data And Expression
Numerical Data And ExpressionNumerical Data And Expression
Numerical Data And ExpressionPRN USM
 
Introduction To Computer and Java
Introduction To Computer and JavaIntroduction To Computer and Java
Introduction To Computer and JavaPRN USM
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...PRN USM
 
Empowering Women Towards Smokefree Homes
Empowering  Women  Towards  Smokefree  HomesEmpowering  Women  Towards  Smokefree  Homes
Empowering Women Towards Smokefree HomesPRN USM
 
Sfe The Singaporean Experience
Sfe The Singaporean ExperienceSfe The Singaporean Experience
Sfe The Singaporean ExperiencePRN USM
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...PRN USM
 
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And PrioritiesMalaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And PrioritiesPRN USM
 
Role Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco ControlRole Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco ControlPRN USM
 
Application Of Grants From Mhpb
Application Of Grants From MhpbApplication Of Grants From Mhpb
Application Of Grants From MhpbPRN USM
 

Plus de PRN USM (19)

Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1
 
File Input & Output
File Input & OutputFile Input & Output
File Input & Output
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
 
Array
ArrayArray
Array
 
Class & Object - Intro
Class & Object - IntroClass & Object - Intro
Class & Object - Intro
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition Structure
 
Selection Control Structures
Selection Control StructuresSelection Control Structures
Selection Control Structures
 
Numerical Data And Expression
Numerical Data And ExpressionNumerical Data And Expression
Numerical Data And Expression
 
Introduction To Computer and Java
Introduction To Computer and JavaIntroduction To Computer and Java
Introduction To Computer and Java
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
 
Empowering Women Towards Smokefree Homes
Empowering  Women  Towards  Smokefree  HomesEmpowering  Women  Towards  Smokefree  Homes
Empowering Women Towards Smokefree Homes
 
Sfe The Singaporean Experience
Sfe The Singaporean ExperienceSfe The Singaporean Experience
Sfe The Singaporean Experience
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
 
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And PrioritiesMalaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
 
Role Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco ControlRole Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco Control
 
Application Of Grants From Mhpb
Application Of Grants From MhpbApplication Of Grants From Mhpb
Application Of Grants From Mhpb
 

Dernier

Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxMusic 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxleah joy valeriano
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsManeerUddin
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 

Dernier (20)

Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxMusic 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture hons
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 

Class & Object - User Defined Method

  • 2. Syntax: Defining Class  General syntax for defining a class is: modifieropt class ClassIdentifier { classMembers: data declarations methods definitions }  Where modifier(s) are used to alter the behavior of the class classMembers consist of data declarations and/or methods definitions. 2
  • 3. Class Definition  A class can contain data declarations and method declarations 3 int size, weight; char category; Data declarations Method declarations
  • 4. UML Design Specification 4 UML Class Diagram Class Name What data does it need? What behaviors will it perform? Public methods Hidden information Instance variables -- memory locations used for storing the information needed. Methods -- blocks of code used to perform a specific task.
  • 5. Class Definition: An Example  public class Rectangle  { // data declarations  private double length;  private double width;  //methods definitions  public Rectangle(double l, double w) // Constructor method  {  length = l;  width = w;  } // Rectangle constructor  public double calculateArea()  {  return length * width;  } // calculateArea  } // Rectangle class 5
  • 6. Method Definition  Example 6  The Method Header modifieropt ResultType MethodName (Formal ParameterList ) public static void main (String argv[ ] ) public void deposit (double amount) public double calculateArea ( ) public void MethodName() // Method Header { // Start of method body } // End of method body
  • 7. Method Header  A method declaration begins with a method header 7 int add (int num1, int num2) method name return type Formal parameter list The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal parameter
  • 8. Method Body  The method header is followed by the method body 8 int add (int num1, int num2) { int sum = num1 + num2; return sum; } The return expression must be consistent with the return type sum is local data Local data are created each time the method is called, and are destroyed when it finishes executing
  • 9. User-Defined Methods  Methods can return zero or one value Value-returning methods ○ Methods that have a return type Void methods ○ Methods that do not have a return type 9
  • 10. calculateArea Method. public double calculateArea() { double area; area = length * width; return area; } 10
  • 11. Return statement  Value-returning method uses a return statement to return its value; it passes a value outside the method.  Syntax:return statement return expr;  Where expr can be: Variable, constant value or expression 11
  • 12. User-Defined Methods  Methods can have zero or >= 1 parameters No parameters ○ Nothing inside bracket in method header 1 or more parameters ○ List the paramater/s inside bracket 12
  • 13. Method Parameters - as input/s to a method public class Rectangle { . . . public void setWidth(double w) { width = w; } public void setLength(double l) { length = l; } . . . } 13
  • 14. Syntax: Formal Parameter List (dataType identifier, dataType identifier....) 14 Note: it can be one or more dataType Eg. setWidth( double w ) int add (int num1, int num2)
  • 15. Creating Rectangle Instances  Create, or instantiate, two instances of the Rectangle class: 15 The objects (instances) store actual values. Rectangle rectangle1 = new Rectangle(30,10); Rectangle rectangle2 = new Rectangle(25, 20);
  • 16. Using Rectangle Instances  We use a method call to ask each object to tell us its area: 16 rectangle1 area 300 rectangle2 area 500Printed output: System.out.println("rectangle1 area " + rectangle1.calculateArea()); System.out.println("rectangle2 area " + rectangle2.calculateArea()); References to objects Method calls
  • 17. Syntax : Object Construction  new ClassName(parameters); Example:  new Rectangle(30, 20);  new Car("BMW 540ti", 2004); Purpose:  To construct a new object, initialize it with the construction parameters, and return a reference to the constructed object. 17
  • 18. The RectangleUser Class Definition public class RectangleUser { public static void main(String argv[]) { Rectangle rectangle1 = new Rectangle(30,10); Rectangle rectangle2 = new Rectangle(25,20); System.out.println("rectangle1 area " + rectangle1.calculateArea()); System.out.println("rectangle2 area " + rectangle2.calculateArea()); } // main() } // RectangleUser 18 An application must have a main() method Object Use Object Creation Class Definition
  • 19. Method Call  Syntax to call a method methodName(actual parameter list); Eg. segi4.setWidth(20.5); obj.add (25, count); 19
  • 20. Formal vs Actual Parameters  When a method is called, the actual parameters in the invocation are copied into the formal parameters in the method header 20 int add (int num1, int num2) { int sum = num1 + num2; return sum; } total = obj.add(25, count);
  • 21.  public class RectangleUser  {  public static void main(String argv[])  {  Rectangle rectangle1 = new Rectangle(30.0,10.0);   System.out.println("rectangle1 area " +  rectangle1.calculateArea()); rectangle1.setWidth(20.0);  System.out.println("rectangle1 area " +  rectangle1.calculateArea());  }  } 21 Formal vs Actual Parameters
  • 22. Method Overloading  In Java, within a class, several methods can have the same name. We called method overloading  Two methods are said to have different formal parameter lists: If both methods have a different number of formal parameters If the number of formal parameters is the same in both methods, the data type of the formal parameters in the order we list must differ in at least one position 22
  • 23. Method Overloading  Example: public void methodABC() public void methodABC(int x) public void methodABC(int x, double y) public void methodABC(double x, int y) public void methodABC(char x, double y) public void methodABC(String x,int y) 23
  • 24. Java code for overloading  public class Exam  {  public static void main (String [] args)  {  int test1=75, test2=68, total_test1, total_test2;  Exam midsem=new Exam();  total_test1 = midsem.result(test1);  System.out.println("Total test 1 : "+ total_test1);  total_test2 = midsem.result(test1,test2);  System.out.println("Total test 2 : "+ total_test2);  }  int result (int i)  {  return i++;  }   int result (int i, int j)  {  return ++i + j;  }  } 24
  • 25.  Output Total test 1 : 75 Total test 2 : 144 25
  • 26. Constructors Revisited  Properties of constructors: Name of constructor same as the name of class A constructor,even though it is a method, it has no type Constructors are automatically executed when a class object is instantiated A class can have more than one constructors – “constructor overloading” ○ which constructor executes depends on the type of value passed to the constructor when the object is instantiated 26
  • 27. Java code (constructor overloading) public class Student { String name; int age; Student(String n, int a) { name = n; age = a; System.out.println ("Name1 :" + name); System.out.println ("Age1 :" + age); } Student(String n) { name = n; age = 18; System.out.println ("Name2 :" + name); System.out.println ("Age2 :" + age); } public static void main (String args[]) { Student myStudent1=new Student("Adam",22); Student myStudent2=new Student("Adlin"); } } 27
  • 29. Object Methods & Class Methods  Object/Instance methods belong to objects and can only be applied after the objects are created.  They called by the following : objectName.methodName();  Class can have its own methods known as class methods or static methods 29
  • 30. Static Methods  Java supports static methods as well as static variables.  Static Method:-  Belongs to class (NOT to objects created from the class)  Can be called without creating an object/instance of the class  To define a static method, put the modifier static in the method declaration:  Static methods are called by : ClassName.methodName(); 30
  • 31. Java Code (static method) public class Fish { public static void main (String args[]) { System.out.println ("Flower Horn"); Fish.colour(); } static void colour () { System.out.println ("Beautiful Colour"); } } 31

Notes de l'éditeur

  1. Ada 2 kategori method 1.Method yg dpt pulangkan nilai-guna return 2.Void methodtak dpt pulangkan nilai
  2. Ada 2 kategori method 1.Method yg dpt pulangkan nilai-guna return 2.Void methodtak dpt pulangkan nilai
  3. Semasa panggilan method dilakukan, boleh ada lebih dari satu jenis data pada parameter.
  4. Sintak untuk memanggil method yang boleh pulangkan nilai (mesti ada parameter semasa panggilan dilakukan)
  5. Method methodABC() merupakan satu contoh method overloading dalam satu kelas