SlideShare une entreprise Scribd logo
1  sur  11
Télécharger pour lire hors ligne
Lesson 2 of 4 Object Oriented Programming in Java
1 of 11
Lesson 2: Methods
Author: Kasun Ranga Wijeweera
Email: krw19870829@gmail.com
Date: 2016 December 13
There are two types of methods: instance methods and class methods.
Let‟s look at instance methods first.
Now modify the files as follows.
Student.java
class Student
{
char name;
int age;
double marksMaths;
double marksEnglish;
double average;
static double avg;
void calAverage()
{
average=(marksMaths+marksEnglish)/2;
}
}
Lesson 2 of 4 Object Oriented Programming in Java
2 of 11
Test.java
class Test
{
public static void main(String args[])
{
Student x1=new Student();
Student x2=new Student();
x1.name='K';
x1.age=23;
x1.marksMaths=45;
x1.marksEnglish=78;
x2.name='S';
x2.age=24;
x2.marksMaths=56;
x2.marksEnglish=98;
x1.calAverage();
x2.calAverage();
System.out.println(x1.average);
System.out.println(x2.average);
}
}
Execution of following two lines will create two objects.
Student x1=new Student();
Student x2=new Student();
Lesson 2 of 4 Object Oriented Programming in Java
3 of 11
Here x1 and x2 store the memory locations of the created two objects
respectively. The attributes of the objects contain their default values.
Following code segment assign user defined values to the attributes.
x1.name='K';
x1.age=23;
x1.marksMaths=45;
x1.marksEnglish=78;
x2.name='S';
x2.age=24;
x2.marksMaths=56;
x2.marksEnglish=98;
The calAverage method is an instance method. That means it always
needs an instance to invoke.
Following line executes the calAverage method with respect to the
object referred by x1.
x1.calAverage();
name = „u0000‟
age = 0
marksMaths = 0.0
marksEnglish = 0.0
average = 0.0
avg = 0.0
name = „u0000‟
age = 0
marksMaths = 0.0
marksEnglish = 0.0
average = 0.0
avg = 0.0
name = „K‟
age = 23
marksMaths = 45
marksEnglish = 78
average = 0.0
avg = 0.0
name = „S‟
age = 24
marksMaths = 56
marksEnglish = 98
average = 0.0
avg = 0.0
x1 x2
x1 x2
Lesson 2 of 4 Object Oriented Programming in Java
4 of 11
Following line executes the calAverage method with respect to the
object referred by x2.
x2.calAverage();
Let‟s look at class methods now. The class methods do not need an
object to invoke.
Modify your code as follows.
Student.java
class Student
{
char name;
int age;
double marksMaths;
double marksEnglish;
double average;
static double avg;
name = „K‟
age = 23
marksMaths = 45
marksEnglish = 78
average = 61.5
avg = 0.0
name = „S‟
age = 24
marksMaths = 56
marksEnglish = 98
average = 77
avg = 0.0
x1
x2
Lesson 2 of 4 Object Oriented Programming in Java
5 of 11
void calAverage()
{
average=(marksMaths+marksEnglish)/2;
}
static void calAvg(Student s[])
{
int i;
for(i=0;i<s.length;i++)
{
avg+=s[i].average;
}
avg/=s.length;
}
}
Test.java
class Test
{
public static void main(String args[])
{
Student x1=new Student();
Student x2=new Student();
x1.name='K';
x1.age=23;
x1.marksMaths=45;
x1.marksEnglish=78;
Lesson 2 of 4 Object Oriented Programming in Java
6 of 11
x2.name='S';
x2.age=24;
x2.marksMaths=56;
x2.marksEnglish=98;
x1.calAverage();
x2.calAverage();
System.out.println(x1.average);
System.out.println(x2.average);
Student x[]=new Student[2];
x[0]=x1;
x[1]=x2;
Student.calAvg(x);
System.out.println(Student.avg);
}
}
The calAvg method is a class method. We have to use keyword static
to denote that it is a class method. It can be invoked as,
Student.calAvg(x);
name = „K‟
age = 23
marksMaths = 45
marksEnglish = 78
average = 61.5
avg = 69.25
name = „S‟
age = 24
marksMaths = 56
marksEnglish = 98
average = 77
avg = 69.25
x1 x2
Lesson 2 of 4 Object Oriented Programming in Java
7 of 11
Each of following two lines also does the same thing as above line.
x1.calAvg(x);
x2.calAvg(x);
An instance method can access all the instance attributes and class
attributes declared in the same class in which the method exists.
A class method can only access class attributes declared in the same
class in which the method exists.
Exercise
Implement getGrade method which returns the grade of a student
using the criteria given in the following table.
Average marks range Grade
average ≥ 70 A
40 ≤ average < 70 B
30 ≤ average < 40 C
average < 30 F
Now let‟s discuss a special kind of method called constructor.
The constructor has two main properties: method name is equal to the
class name, no return type.
A constructor can be used to create objects from the class while
assigning user defined values to the attributes.
Modify the files as follows.
Lesson 2 of 4 Object Oriented Programming in Java
8 of 11
Student.java
class Student
{
char name;
int age;
double marksMaths;
double marksEnglish;
double average;
static double avg;
Student(char name, int age, double marksMaths, double
marksEnglish)
{
this.name=name;
this.age=age;
this.marksMaths=marksMaths;
this.marksEnglish=marksEnglish;
}
}
Test.java
class Test
{
public static void main(String args[])
{
Student y1=new Student('K',23,45,78);
Student y2=new Student('S',24,56,98);
}
}
Lesson 2 of 4 Object Oriented Programming in Java
9 of 11
This time two objects will be created with user defined values for
attributes as follows.
Keyword this in java: this is a reference variable that refers to the
current object.
Now again modify Test.java file only as follows.
Test.java
class Test
{
public static void main(String args[])
{
Student y1=new Student('K',23,45,78);
Student y2=new Student('S',24,56,98);
Student y=new Student();
}
}
This time you will see an error after compiling as shown in the figure
below.
name = „K‟
age = 23
marksMaths = 45
marksEnglish = 78
average = 0.0
avg = 0.0
name = „S‟
age = 24
marksMaths = 56
marksEnglish = 98
average = 0.0
avg = 0.0
y1 y2
Lesson 2 of 4 Object Oriented Programming in Java
10 of 11
Default constructor: A constructor that is automatically generated by
the compiler in the absence of any programmer-defined constructors.
Actually what we were using as Student() is the default constructor. It
is invisible and automatically generated in the absence of any
programmer-defined constructors. It is not generated if the
programmer has defined at least one constructor. That is why we got
an error this time. If we need a constructor which does the same thing
as the default constructor we have to modify the class Test.java as
given below.
Test.java
class Student
{
char name;
int age;
double marksMaths;
double marksEnglish;
double average;
static double avg;
Lesson 2 of 4 Object Oriented Programming in Java
11 of 11
Student(char name, int age, double marksMaths, double
marksEnglish)
{
this.name=name;
this.age=age;
this.marksMaths=marksMaths;
this.marksEnglish=marksEnglish;
}
Student()
{
}
}
The constructor with empty parameter list and empty body will assign
default values to the attributes and behaves like default constructor.
Now you are not going to see the previous error.
Note that now there are two constructors with the same name.
However the compiler distinguishes the two constructors using the
different parameter lists. This is called “constructor overloading”.
Method overloading: Having more than one method with the same
name, but different method signatures.
Exercise
Implement a method to display the values of attributes in each object.

Contenu connexe

Tendances

Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
Abhilash Nair
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
Sunil Kumar Gunasekaran
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
backdoor
 
Java lec class, objects and constructors
Java lec class, objects and constructorsJava lec class, objects and constructors
Java lec class, objects and constructors
Jan Niño Acierto
 

Tendances (20)

Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Java basic
Java basicJava basic
Java basic
 
Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
ITFT-Classes and object in java
ITFT-Classes and object in javaITFT-Classes and object in java
ITFT-Classes and object in java
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Access modifiers
Access modifiersAccess modifiers
Access modifiers
 
Java chapter 4
Java chapter 4Java chapter 4
Java chapter 4
 
Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
Oops in java
Oops in javaOops in java
Oops in java
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
 
Delphi qa
Delphi qaDelphi qa
Delphi qa
 
C# Types of classes
C# Types of classesC# Types of classes
C# Types of classes
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Principles of Object Oriented Programming
Principles of Object Oriented ProgrammingPrinciples of Object Oriented Programming
Principles of Object Oriented Programming
 
Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in Python
 
Java lec class, objects and constructors
Java lec class, objects and constructorsJava lec class, objects and constructors
Java lec class, objects and constructors
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 

En vedette

Improving the accuracy of k-means algorithm using genetic algorithm
Improving the accuracy of k-means algorithm using genetic algorithmImproving the accuracy of k-means algorithm using genetic algorithm
Improving the accuracy of k-means algorithm using genetic algorithm
Kasun Ranga Wijeweera
 
Linked List Implementation of Stack in C
Linked List Implementation of Stack in CLinked List Implementation of Stack in C
Linked List Implementation of Stack in C
Kasun Ranga Wijeweera
 
Digital Differential Analyzer Line Drawing Algorithm in C
Digital Differential Analyzer Line Drawing Algorithm in CDigital Differential Analyzer Line Drawing Algorithm in C
Digital Differential Analyzer Line Drawing Algorithm in C
Kasun Ranga Wijeweera
 
Implementation of k-means clustering algorithm in C
Implementation of k-means clustering algorithm in CImplementation of k-means clustering algorithm in C
Implementation of k-means clustering algorithm in C
Kasun Ranga Wijeweera
 
Linked List Implementation of Deque in C
Linked List Implementation of Deque in CLinked List Implementation of Deque in C
Linked List Implementation of Deque in C
Kasun Ranga Wijeweera
 
Linked List Implementation of Queue in C
Linked List Implementation of Queue in CLinked List Implementation of Queue in C
Linked List Implementation of Queue in C
Kasun Ranga Wijeweera
 

En vedette (14)

Improving the accuracy of k-means algorithm using genetic algorithm
Improving the accuracy of k-means algorithm using genetic algorithmImproving the accuracy of k-means algorithm using genetic algorithm
Improving the accuracy of k-means algorithm using genetic algorithm
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Computing the Area of a Polygon
Computing the Area of a PolygonComputing the Area of a Polygon
Computing the Area of a Polygon
 
Flood Filling Algorithm in C
Flood Filling Algorithm in CFlood Filling Algorithm in C
Flood Filling Algorithm in C
 
Wave ECG
Wave ECGWave ECG
Wave ECG
 
Exercises for Two Dimensional Geometric Transformations
Exercises for Two Dimensional Geometric TransformationsExercises for Two Dimensional Geometric Transformations
Exercises for Two Dimensional Geometric Transformations
 
Linked List Implementation of Stack in C
Linked List Implementation of Stack in CLinked List Implementation of Stack in C
Linked List Implementation of Stack in C
 
Digital Differential Analyzer Line Drawing Algorithm in C
Digital Differential Analyzer Line Drawing Algorithm in CDigital Differential Analyzer Line Drawing Algorithm in C
Digital Differential Analyzer Line Drawing Algorithm in C
 
Exercises for Convexity of Polygons
Exercises for Convexity of PolygonsExercises for Convexity of Polygons
Exercises for Convexity of Polygons
 
Implementation of k-means clustering algorithm in C
Implementation of k-means clustering algorithm in CImplementation of k-means clustering algorithm in C
Implementation of k-means clustering algorithm in C
 
Linked List Implementation of Deque in C
Linked List Implementation of Deque in CLinked List Implementation of Deque in C
Linked List Implementation of Deque in C
 
Boundary Fill Algorithm in C
Boundary Fill Algorithm in CBoundary Fill Algorithm in C
Boundary Fill Algorithm in C
 
Digital Differential Analyzer Line Drawing Algorithm
Digital Differential Analyzer Line Drawing AlgorithmDigital Differential Analyzer Line Drawing Algorithm
Digital Differential Analyzer Line Drawing Algorithm
 
Linked List Implementation of Queue in C
Linked List Implementation of Queue in CLinked List Implementation of Queue in C
Linked List Implementation of Queue in C
 

Similaire à Methods in Java

Functions and Objects in JavaScript
Functions and Objects in JavaScript Functions and Objects in JavaScript
Functions and Objects in JavaScript
Dhananjay Kumar
 
I have a Student.java class constructor like thisAnd I need to re.pdf
I have a Student.java class constructor like thisAnd I need to re.pdfI have a Student.java class constructor like thisAnd I need to re.pdf
I have a Student.java class constructor like thisAnd I need to re.pdf
arorastores
 
Java căn bản - Chapter2
Java căn bản - Chapter2Java căn bản - Chapter2
Java căn bản - Chapter2
Vince Vo
 

Similaire à Methods in Java (20)

Functions and Objects in JavaScript
Functions and Objects in JavaScript Functions and Objects in JavaScript
Functions and Objects in JavaScript
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptx
 
A457405934_21789_26_2018_Inheritance.ppt
A457405934_21789_26_2018_Inheritance.pptA457405934_21789_26_2018_Inheritance.ppt
A457405934_21789_26_2018_Inheritance.ppt
 
constructer.pptx
constructer.pptxconstructer.pptx
constructer.pptx
 
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
I have a Student.java class constructor like thisAnd I need to re.pdf
I have a Student.java class constructor like thisAnd I need to re.pdfI have a Student.java class constructor like thisAnd I need to re.pdf
I have a Student.java class constructor like thisAnd I need to re.pdf
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
4.Packages_m1.ppt
4.Packages_m1.ppt4.Packages_m1.ppt
4.Packages_m1.ppt
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3
 
Classes, objects, methods, constructors, this keyword in java
Classes, objects, methods, constructors, this keyword  in javaClasses, objects, methods, constructors, this keyword  in java
Classes, objects, methods, constructors, this keyword in java
 
OOP with Java - continued
OOP with Java - continuedOOP with Java - continued
OOP with Java - continued
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
 
DAY_1.1.pptx
DAY_1.1.pptxDAY_1.1.pptx
DAY_1.1.pptx
 
Unit 2 notes.pdf
Unit 2 notes.pdfUnit 2 notes.pdf
Unit 2 notes.pdf
 
Unit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptxUnit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptx
 
Java căn bản - Chapter2
Java căn bản - Chapter2Java căn bản - Chapter2
Java căn bản - Chapter2
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with Java
 
OOP with Java - Continued
OOP with Java - Continued OOP with Java - Continued
OOP with Java - Continued
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 

Plus de Kasun Ranga Wijeweera

Plus de Kasun Ranga Wijeweera (20)

Decorator Design Pattern in C#
Decorator Design Pattern in C#Decorator Design Pattern in C#
Decorator Design Pattern in C#
 
Singleton Design Pattern in C#
Singleton Design Pattern in C#Singleton Design Pattern in C#
Singleton Design Pattern in C#
 
Introduction to Design Patterns
Introduction to Design PatternsIntroduction to Design Patterns
Introduction to Design Patterns
 
Algorithms for Convex Partitioning of a Polygon
Algorithms for Convex Partitioning of a PolygonAlgorithms for Convex Partitioning of a Polygon
Algorithms for Convex Partitioning of a Polygon
 
Geometric Transformations II
Geometric Transformations IIGeometric Transformations II
Geometric Transformations II
 
Geometric Transformations I
Geometric Transformations IGeometric Transformations I
Geometric Transformations I
 
Introduction to Polygons
Introduction to PolygonsIntroduction to Polygons
Introduction to Polygons
 
Bresenham Line Drawing Algorithm
Bresenham Line Drawing AlgorithmBresenham Line Drawing Algorithm
Bresenham Line Drawing Algorithm
 
Digital Differential Analyzer Line Drawing Algorithm
Digital Differential Analyzer Line Drawing AlgorithmDigital Differential Analyzer Line Drawing Algorithm
Digital Differential Analyzer Line Drawing Algorithm
 
Loops in Visual Basic: Exercises
Loops in Visual Basic: ExercisesLoops in Visual Basic: Exercises
Loops in Visual Basic: Exercises
 
Conditional Logic: Exercises
Conditional Logic: ExercisesConditional Logic: Exercises
Conditional Logic: Exercises
 
Getting Started with Visual Basic Programming
Getting Started with Visual Basic ProgrammingGetting Started with Visual Basic Programming
Getting Started with Visual Basic Programming
 
CheckBoxes and RadioButtons
CheckBoxes and RadioButtonsCheckBoxes and RadioButtons
CheckBoxes and RadioButtons
 
Variables in Visual Basic Programming
Variables in Visual Basic ProgrammingVariables in Visual Basic Programming
Variables in Visual Basic Programming
 
Loops in Visual Basic Programming
Loops in Visual Basic ProgrammingLoops in Visual Basic Programming
Loops in Visual Basic Programming
 
Conditional Logic in Visual Basic Programming
Conditional Logic in Visual Basic ProgrammingConditional Logic in Visual Basic Programming
Conditional Logic in Visual Basic Programming
 
Assignment for Variables
Assignment for VariablesAssignment for Variables
Assignment for Variables
 
Assignment for Factory Method Design Pattern in C# [ANSWERS]
Assignment for Factory Method Design Pattern in C# [ANSWERS]Assignment for Factory Method Design Pattern in C# [ANSWERS]
Assignment for Factory Method Design Pattern in C# [ANSWERS]
 
Assignment for Events
Assignment for EventsAssignment for Events
Assignment for Events
 
Mastering Arrays Assignment
Mastering Arrays AssignmentMastering Arrays Assignment
Mastering Arrays Assignment
 

Dernier

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Dernier (20)

Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 

Methods in Java

  • 1. Lesson 2 of 4 Object Oriented Programming in Java 1 of 11 Lesson 2: Methods Author: Kasun Ranga Wijeweera Email: krw19870829@gmail.com Date: 2016 December 13 There are two types of methods: instance methods and class methods. Let‟s look at instance methods first. Now modify the files as follows. Student.java class Student { char name; int age; double marksMaths; double marksEnglish; double average; static double avg; void calAverage() { average=(marksMaths+marksEnglish)/2; } }
  • 2. Lesson 2 of 4 Object Oriented Programming in Java 2 of 11 Test.java class Test { public static void main(String args[]) { Student x1=new Student(); Student x2=new Student(); x1.name='K'; x1.age=23; x1.marksMaths=45; x1.marksEnglish=78; x2.name='S'; x2.age=24; x2.marksMaths=56; x2.marksEnglish=98; x1.calAverage(); x2.calAverage(); System.out.println(x1.average); System.out.println(x2.average); } } Execution of following two lines will create two objects. Student x1=new Student(); Student x2=new Student();
  • 3. Lesson 2 of 4 Object Oriented Programming in Java 3 of 11 Here x1 and x2 store the memory locations of the created two objects respectively. The attributes of the objects contain their default values. Following code segment assign user defined values to the attributes. x1.name='K'; x1.age=23; x1.marksMaths=45; x1.marksEnglish=78; x2.name='S'; x2.age=24; x2.marksMaths=56; x2.marksEnglish=98; The calAverage method is an instance method. That means it always needs an instance to invoke. Following line executes the calAverage method with respect to the object referred by x1. x1.calAverage(); name = „u0000‟ age = 0 marksMaths = 0.0 marksEnglish = 0.0 average = 0.0 avg = 0.0 name = „u0000‟ age = 0 marksMaths = 0.0 marksEnglish = 0.0 average = 0.0 avg = 0.0 name = „K‟ age = 23 marksMaths = 45 marksEnglish = 78 average = 0.0 avg = 0.0 name = „S‟ age = 24 marksMaths = 56 marksEnglish = 98 average = 0.0 avg = 0.0 x1 x2 x1 x2
  • 4. Lesson 2 of 4 Object Oriented Programming in Java 4 of 11 Following line executes the calAverage method with respect to the object referred by x2. x2.calAverage(); Let‟s look at class methods now. The class methods do not need an object to invoke. Modify your code as follows. Student.java class Student { char name; int age; double marksMaths; double marksEnglish; double average; static double avg; name = „K‟ age = 23 marksMaths = 45 marksEnglish = 78 average = 61.5 avg = 0.0 name = „S‟ age = 24 marksMaths = 56 marksEnglish = 98 average = 77 avg = 0.0 x1 x2
  • 5. Lesson 2 of 4 Object Oriented Programming in Java 5 of 11 void calAverage() { average=(marksMaths+marksEnglish)/2; } static void calAvg(Student s[]) { int i; for(i=0;i<s.length;i++) { avg+=s[i].average; } avg/=s.length; } } Test.java class Test { public static void main(String args[]) { Student x1=new Student(); Student x2=new Student(); x1.name='K'; x1.age=23; x1.marksMaths=45; x1.marksEnglish=78;
  • 6. Lesson 2 of 4 Object Oriented Programming in Java 6 of 11 x2.name='S'; x2.age=24; x2.marksMaths=56; x2.marksEnglish=98; x1.calAverage(); x2.calAverage(); System.out.println(x1.average); System.out.println(x2.average); Student x[]=new Student[2]; x[0]=x1; x[1]=x2; Student.calAvg(x); System.out.println(Student.avg); } } The calAvg method is a class method. We have to use keyword static to denote that it is a class method. It can be invoked as, Student.calAvg(x); name = „K‟ age = 23 marksMaths = 45 marksEnglish = 78 average = 61.5 avg = 69.25 name = „S‟ age = 24 marksMaths = 56 marksEnglish = 98 average = 77 avg = 69.25 x1 x2
  • 7. Lesson 2 of 4 Object Oriented Programming in Java 7 of 11 Each of following two lines also does the same thing as above line. x1.calAvg(x); x2.calAvg(x); An instance method can access all the instance attributes and class attributes declared in the same class in which the method exists. A class method can only access class attributes declared in the same class in which the method exists. Exercise Implement getGrade method which returns the grade of a student using the criteria given in the following table. Average marks range Grade average ≥ 70 A 40 ≤ average < 70 B 30 ≤ average < 40 C average < 30 F Now let‟s discuss a special kind of method called constructor. The constructor has two main properties: method name is equal to the class name, no return type. A constructor can be used to create objects from the class while assigning user defined values to the attributes. Modify the files as follows.
  • 8. Lesson 2 of 4 Object Oriented Programming in Java 8 of 11 Student.java class Student { char name; int age; double marksMaths; double marksEnglish; double average; static double avg; Student(char name, int age, double marksMaths, double marksEnglish) { this.name=name; this.age=age; this.marksMaths=marksMaths; this.marksEnglish=marksEnglish; } } Test.java class Test { public static void main(String args[]) { Student y1=new Student('K',23,45,78); Student y2=new Student('S',24,56,98); } }
  • 9. Lesson 2 of 4 Object Oriented Programming in Java 9 of 11 This time two objects will be created with user defined values for attributes as follows. Keyword this in java: this is a reference variable that refers to the current object. Now again modify Test.java file only as follows. Test.java class Test { public static void main(String args[]) { Student y1=new Student('K',23,45,78); Student y2=new Student('S',24,56,98); Student y=new Student(); } } This time you will see an error after compiling as shown in the figure below. name = „K‟ age = 23 marksMaths = 45 marksEnglish = 78 average = 0.0 avg = 0.0 name = „S‟ age = 24 marksMaths = 56 marksEnglish = 98 average = 0.0 avg = 0.0 y1 y2
  • 10. Lesson 2 of 4 Object Oriented Programming in Java 10 of 11 Default constructor: A constructor that is automatically generated by the compiler in the absence of any programmer-defined constructors. Actually what we were using as Student() is the default constructor. It is invisible and automatically generated in the absence of any programmer-defined constructors. It is not generated if the programmer has defined at least one constructor. That is why we got an error this time. If we need a constructor which does the same thing as the default constructor we have to modify the class Test.java as given below. Test.java class Student { char name; int age; double marksMaths; double marksEnglish; double average; static double avg;
  • 11. Lesson 2 of 4 Object Oriented Programming in Java 11 of 11 Student(char name, int age, double marksMaths, double marksEnglish) { this.name=name; this.age=age; this.marksMaths=marksMaths; this.marksEnglish=marksEnglish; } Student() { } } The constructor with empty parameter list and empty body will assign default values to the attributes and behaves like default constructor. Now you are not going to see the previous error. Note that now there are two constructors with the same name. However the compiler distinguishes the two constructors using the different parameter lists. This is called “constructor overloading”. Method overloading: Having more than one method with the same name, but different method signatures. Exercise Implement a method to display the values of attributes in each object.