SlideShare une entreprise Scribd logo
1  sur  9
Télécharger pour lire hors ligne
Lesson 1 of 4 Object Oriented Programming in Java
1 of 9
Lesson 1: Classes and Objects
Author: Kasun Ranga Wijeweera
Email: krw19870829@gmail.com
Date: 2016 December 12
There are students and teachers in an educational institute. The
institute conducts a course which consists of two subjects:
Mathematics and English. The students have to sit for two
examinations at the end the course. The students are graded based on
their average marks. The salary of a teacher is computed from the
number of teaching hours. Suppose we have to develop an
information system for this institute.
Class: A template that represents the entities with common attributes
and methods.
Therefore we can identify two classes: Student and Teacher.
Attributes of the class Student: name, age, marksMaths,
marksEnglish, average, avg
Attributes of the class Teacher: name, age, hours, rate, salary
Student
name
age
marksMaths
marksEnglish
average
avg
calAverage
getGrade
calAvg
Teacher
name
age
hours
rate
salary
calSalary
Lesson 1 of 4 Object Oriented Programming in Java
2 of 9
Methods of the class Student: calAverage, getGrade, calAvg
Methods of the class Teacher: calSalary
Object: Object is an instance of a class.
Following is an example for an object of class Student.
The attributes: name, age, marksMaths, marksEnglish are given as
inputs when creating the object. The attributes: average, avg should
be computed by the system. Here the values of attributes: average,
avg have not yet been computed and they store their default values.
What is the difference between a class and an object? Class does not
have values assigned to the attributes whereas the objects have.
What is a java program? A Collection of classes is called a java
program.
The set of attributes and the set of methods of a class are called state
and behavior of the class respectively.
There are eight primitive data types in java: boolean, byte, char,
short, int, long, float, double.
name = ‘A’
age = 23
marksMaths = 67
marksEnglish = 84
average = 0.0
avg = 0.0
Lesson 1 of 4 Object Oriented Programming in Java
3 of 9
Data Type Default Value
boolean false
byte 0
char ‘u0000’
short 0
int 0
long 0L
float 0.0f
double 0.0d
Now let’s try to implement using java programming language. Create
a folder called Codes. Create two java files called Student.java and
Test.java inside that folder. The contents of those files should be as
follows.
Student.java
class Student
{
char name;
int age;
double marksMaths;
double marksEnglish;
double average;
}
Test.java
class Test
{
public static void main(String args[])
{
}
}
Lesson 1 of 4 Object Oriented Programming in Java
4 of 9
We have not yet included everything inside the class Student for the
time being. The class Test contains the main method. We have to
compile and run the class Test only. You have to use Command
Prompt to compile and run. You must be inside the folder Codes in
order to do that.
Example
D:LGOOPNotesCodes>javac Test.java
D:LGOOPNotesCodes>java Test
The first line compiles the code and the second line runs the code.
You have to use command cd to go inside the folder Codes. The
following figure explains this further.
Driver class: The class in which the main method exists.
Here Test.java is our driver class. Every program must have exactly
one driver class. The execution of the program begins inside the body
of the main method.
Lesson 1 of 4 Object Oriented Programming in Java
5 of 9
We can create an object from our class Student as follows.
Student s;
s = new Student();
The first line declares a variable of type Student. It is called a
reference variable and created on stack memory. It behaves like
normal variables int x, double y, etc. In the second line, the keyword
new creates an object of type Student and assigns its memory location
to the reference variable s. Note that the objects are always created on
the heap memory.
Then modify your Test.java file as follows and again compile & run.
Test.java
class Test
{
public static void main(String args[])
{
Student s;
s=new Student();
System.out.println(s.name);
System.out.println(s.age);
System.out.println(s.marksMaths);
System.out.println(s.marksEnglish);
System.out.println(s.average);
}
}
We can use dot operator (.) to access attributes of an object.
Following figure shows the output in Command Prompt.
Lesson 1 of 4 Object Oriented Programming in Java
6 of 9
We did not assign values to the attributes of the object. Therefore java
automatically assigns default values to the attributes.
We can use dot operator to assign values to the attributes of an object
as well. Then Test.java file is as follows.
Lesson 1 of 4 Object Oriented Programming in Java
7 of 9
Test.java
class Test
{
public static void main(String args[])
{
Student s;
s=new Student();
s.name='A';
s.age=23;
marksMaths=67;
marksEnglish=84;
System.out.println(s.name);
System.out.println(s.age);
System.out.println(s.marksMaths);
System.out.println(s.marksEnglish);
System.out.println(s.average);
}
}
Exercise
1. Create following Student objects. We have already created the
first one.
Object name age marksMaths marksEnglish
s ‘A’ 23 67 64
s1 ‘B’ 34 45 88
s2 ‘C’ 22 29 93
s3 ‘D’ 17 74 38
2. Compute the value of the attribute average for each object.
Lesson 1 of 4 Object Oriented Programming in Java
8 of 9
Suppose we execute following line of code.
s = s1
Now the variable s stores the memory location of the object with the
name ‘B’. And the variable s1 also stores the memory location of the
object with the name ‘B’. However no variable stores the memory
location of the object with the name ‘A’. Therefore the object with the
name ‘A’ will be destroyed from the memory.
The objects without references are automatically deleted from the
memory.
The attributes can be divided into two categories.
Instance attribute: An instance attribute is an attribute defined in a
class for which each object of the class has a separate copy.
Class attribute: A class attribute is an attribute defined in a class of
which a single copy exists, regardless of how many objects of the
class exist.
The attributes: name, age, marksMaths, marksEnglish, average are
examples for instance attributes. The attribute avg is used to store the
average of average marks of each student. There is one avg value for
all the students and it should be a class attribute. We use keyword
static to distinguish class attributes.
Lesson 1 of 4 Object Oriented Programming in Java
9 of 9
Now modify the two files as follows.
Student.java
class Student
{
char name;
int age;
double marksMaths;
double marksEnglish;
double average;
static double avg;
}
Test.java
class Test
{
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
s1.avg=10;
System.out.println(s2.avg);
}
}
This will give 10.0 as the output. The avg variable is common to all
the objects. Therefore following three lines do the same thing.
s1.avg
s2.avg
Student.avg

Contenu connexe

Tendances

Classes and objects
Classes and objectsClasses and objects
Classes and objectsNilesh Dalvi
 
Introduction to Classes and Objects in Java - Edufect
Introduction to Classes and Objects in Java - EdufectIntroduction to Classes and Objects in Java - Edufect
Introduction to Classes and Objects in Java - EdufectEdufect
 
2 lesson 2 object oriented programming in c++
2 lesson 2 object oriented programming in c++2 lesson 2 object oriented programming in c++
2 lesson 2 object oriented programming in c++Jeff TUYISHIME
 
Classes cpp intro thomson bayan college
Classes cpp  intro thomson bayan collegeClasses cpp  intro thomson bayan college
Classes cpp intro thomson bayan collegeahmed hmed
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++Muhammad Waqas
 
object oriented programming using c++
 object oriented programming using c++ object oriented programming using c++
object oriented programming using c++fasalsial1fasalsial1
 
ITFT-Classes and object in java
ITFT-Classes and object in javaITFT-Classes and object in java
ITFT-Classes and object in javaAtul Sehdev
 
Lect 1-class and object
Lect 1-class and objectLect 1-class and object
Lect 1-class and objectFajar Baskoro
 
Java class,object,method introduction
Java class,object,method introductionJava class,object,method introduction
Java class,object,method introductionSohanur63
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classesFajar Baskoro
 

Tendances (20)

Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Introduction to Classes and Objects in Java - Edufect
Introduction to Classes and Objects in Java - EdufectIntroduction to Classes and Objects in Java - Edufect
Introduction to Classes and Objects in Java - Edufect
 
2 lesson 2 object oriented programming in c++
2 lesson 2 object oriented programming in c++2 lesson 2 object oriented programming in c++
2 lesson 2 object oriented programming in c++
 
Classes cpp intro thomson bayan college
Classes cpp  intro thomson bayan collegeClasses cpp  intro thomson bayan college
Classes cpp intro thomson bayan college
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
 
Classes and objects in c++
Classes and objects in c++Classes and objects in c++
Classes and objects in c++
 
object oriented programming using c++
 object oriented programming using c++ object oriented programming using c++
object oriented programming using c++
 
Chapter 7 java
Chapter 7 javaChapter 7 java
Chapter 7 java
 
Java Notes
Java NotesJava Notes
Java Notes
 
ITFT-Classes and object in java
ITFT-Classes and object in javaITFT-Classes and object in java
ITFT-Classes and object in java
 
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
 
Classes and objects in java
Classes and objects in javaClasses and objects in java
Classes and objects in java
 
Lect 1-class and object
Lect 1-class and objectLect 1-class and object
Lect 1-class and object
 
C++ classes
C++ classesC++ classes
C++ classes
 
Java class,object,method introduction
Java class,object,method introductionJava class,object,method introduction
Java class,object,method introduction
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
6. static keyword
6. static keyword6. static keyword
6. static keyword
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classes
 
C++ And Object in lecture3
C++  And Object in lecture3C++  And Object in lecture3
C++ And Object in lecture3
 
CLASS & OBJECT IN JAVA
CLASS & OBJECT  IN JAVACLASS & OBJECT  IN JAVA
CLASS & OBJECT IN JAVA
 

En vedette

Exercises for Two Dimensional Geometric Transformations
Exercises for Two Dimensional Geometric TransformationsExercises for Two Dimensional Geometric Transformations
Exercises for Two Dimensional Geometric TransformationsKasun 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 CKasun Ranga Wijeweera
 
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 algorithmKasun 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 CKasun 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 CKasun Ranga Wijeweera
 
Principles of Object Oriented Programming
Principles of Object Oriented ProgrammingPrinciples of Object Oriented Programming
Principles of Object Oriented ProgrammingKasun 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 CKasun Ranga Wijeweera
 
Digital Differential Analyzer Line Drawing Algorithm
Digital Differential Analyzer Line Drawing AlgorithmDigital Differential Analyzer Line Drawing Algorithm
Digital Differential Analyzer Line Drawing AlgorithmKasun 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 CKasun Ranga Wijeweera
 

En vedette (15)

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
 
Flood Filling Algorithm in C
Flood Filling Algorithm in CFlood Filling Algorithm in C
Flood Filling Algorithm in C
 
Computing the Area of a Polygon
Computing the Area of a PolygonComputing the Area of a Polygon
Computing the Area of a Polygon
 
Wave ECG
Wave ECGWave ECG
Wave ECG
 
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
 
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
 
Access modifiers
Access modifiersAccess modifiers
Access modifiers
 
Principles of Object Oriented Programming
Principles of Object Oriented ProgrammingPrinciples of Object Oriented Programming
Principles of Object Oriented Programming
 
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 à Classes and objects

packages and interfaces
packages and interfacespackages and interfaces
packages and interfacesmadhavi patil
 
Object oriented programming tutorial
Object oriented programming tutorialObject oriented programming tutorial
Object oriented programming tutorialGhulam Abbas Khan
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programmingshinyduela
 
A457405934_21789_26_2018_Inheritance.ppt
A457405934_21789_26_2018_Inheritance.pptA457405934_21789_26_2018_Inheritance.ppt
A457405934_21789_26_2018_Inheritance.pptRithwikRanjan
 
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.pptxDrYogeshDeshmukh1
 
Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Uzair Salman
 
Classes-and-Object.pptx
Classes-and-Object.pptxClasses-and-Object.pptx
Classes-and-Object.pptxVishwanathanS5
 
09slide.ppt oops classes and objects concept
09slide.ppt oops classes and objects concept09slide.ppt oops classes and objects concept
09slide.ppt oops classes and objects conceptkavitamittal18
 
Java căn bản - Chapter13
Java căn bản - Chapter13Java căn bản - Chapter13
Java căn bản - Chapter13Vince Vo
 
Chapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismChapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismEduardo Bergavera
 

Similaire à Classes and objects (20)

javaopps concepts
javaopps conceptsjavaopps concepts
javaopps concepts
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
Computer Programming 2
Computer Programming 2 Computer Programming 2
Computer Programming 2
 
Object oriented programming tutorial
Object oriented programming tutorialObject oriented programming tutorial
Object oriented programming tutorial
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programming
 
Oop java
Oop javaOop java
Oop java
 
A457405934_21789_26_2018_Inheritance.ppt
A457405934_21789_26_2018_Inheritance.pptA457405934_21789_26_2018_Inheritance.ppt
A457405934_21789_26_2018_Inheritance.ppt
 
JAVA PPT -2 BY ADI.pdf
JAVA PPT -2 BY ADI.pdfJAVA PPT -2 BY ADI.pdf
JAVA PPT -2 BY ADI.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
 
Oop
OopOop
Oop
 
Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes
 
Unit 2 notes.pdf
Unit 2 notes.pdfUnit 2 notes.pdf
Unit 2 notes.pdf
 
slides 01.ppt
slides 01.pptslides 01.ppt
slides 01.ppt
 
4.Packages_m1.ppt
4.Packages_m1.ppt4.Packages_m1.ppt
4.Packages_m1.ppt
 
Classes-and-Object.pptx
Classes-and-Object.pptxClasses-and-Object.pptx
Classes-and-Object.pptx
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
09slide.ppt
09slide.ppt09slide.ppt
09slide.ppt
 
09slide.ppt oops classes and objects concept
09slide.ppt oops classes and objects concept09slide.ppt oops classes and objects concept
09slide.ppt oops classes and objects concept
 
Java căn bản - Chapter13
Java căn bản - Chapter13Java căn bản - Chapter13
Java căn bản - Chapter13
 
Chapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismChapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and Polymorphism
 

Plus de Kasun Ranga Wijeweera

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 PolygonKasun Ranga Wijeweera
 
Digital Differential Analyzer Line Drawing Algorithm
Digital Differential Analyzer Line Drawing AlgorithmDigital Differential Analyzer Line Drawing Algorithm
Digital Differential Analyzer Line Drawing AlgorithmKasun Ranga Wijeweera
 
Getting Started with Visual Basic Programming
Getting Started with Visual Basic ProgrammingGetting Started with Visual Basic Programming
Getting Started with Visual Basic ProgrammingKasun Ranga Wijeweera
 
Variables in Visual Basic Programming
Variables in Visual Basic ProgrammingVariables in Visual Basic Programming
Variables in Visual Basic ProgrammingKasun Ranga Wijeweera
 
Conditional Logic in Visual Basic Programming
Conditional Logic in Visual Basic ProgrammingConditional Logic in Visual Basic Programming
Conditional Logic in Visual Basic ProgrammingKasun Ranga Wijeweera
 
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]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

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 ApplicationsAlberto González Trastoy
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
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...kellynguyen01
 
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 CCTVshikhaohhpro
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
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 PrecisionSolGuruz
 
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.comFatema Valibhai
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
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.pdfkalichargn70th171
 
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.pdfkalichargn70th171
 
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...ICS
 
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 AIABDERRAOUF MEHENNI
 

Dernier (20)

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
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
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...
 
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
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
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
 
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
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
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
 
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
 
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...
 
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
 

Classes and objects

  • 1. Lesson 1 of 4 Object Oriented Programming in Java 1 of 9 Lesson 1: Classes and Objects Author: Kasun Ranga Wijeweera Email: krw19870829@gmail.com Date: 2016 December 12 There are students and teachers in an educational institute. The institute conducts a course which consists of two subjects: Mathematics and English. The students have to sit for two examinations at the end the course. The students are graded based on their average marks. The salary of a teacher is computed from the number of teaching hours. Suppose we have to develop an information system for this institute. Class: A template that represents the entities with common attributes and methods. Therefore we can identify two classes: Student and Teacher. Attributes of the class Student: name, age, marksMaths, marksEnglish, average, avg Attributes of the class Teacher: name, age, hours, rate, salary Student name age marksMaths marksEnglish average avg calAverage getGrade calAvg Teacher name age hours rate salary calSalary
  • 2. Lesson 1 of 4 Object Oriented Programming in Java 2 of 9 Methods of the class Student: calAverage, getGrade, calAvg Methods of the class Teacher: calSalary Object: Object is an instance of a class. Following is an example for an object of class Student. The attributes: name, age, marksMaths, marksEnglish are given as inputs when creating the object. The attributes: average, avg should be computed by the system. Here the values of attributes: average, avg have not yet been computed and they store their default values. What is the difference between a class and an object? Class does not have values assigned to the attributes whereas the objects have. What is a java program? A Collection of classes is called a java program. The set of attributes and the set of methods of a class are called state and behavior of the class respectively. There are eight primitive data types in java: boolean, byte, char, short, int, long, float, double. name = ‘A’ age = 23 marksMaths = 67 marksEnglish = 84 average = 0.0 avg = 0.0
  • 3. Lesson 1 of 4 Object Oriented Programming in Java 3 of 9 Data Type Default Value boolean false byte 0 char ‘u0000’ short 0 int 0 long 0L float 0.0f double 0.0d Now let’s try to implement using java programming language. Create a folder called Codes. Create two java files called Student.java and Test.java inside that folder. The contents of those files should be as follows. Student.java class Student { char name; int age; double marksMaths; double marksEnglish; double average; } Test.java class Test { public static void main(String args[]) { } }
  • 4. Lesson 1 of 4 Object Oriented Programming in Java 4 of 9 We have not yet included everything inside the class Student for the time being. The class Test contains the main method. We have to compile and run the class Test only. You have to use Command Prompt to compile and run. You must be inside the folder Codes in order to do that. Example D:LGOOPNotesCodes>javac Test.java D:LGOOPNotesCodes>java Test The first line compiles the code and the second line runs the code. You have to use command cd to go inside the folder Codes. The following figure explains this further. Driver class: The class in which the main method exists. Here Test.java is our driver class. Every program must have exactly one driver class. The execution of the program begins inside the body of the main method.
  • 5. Lesson 1 of 4 Object Oriented Programming in Java 5 of 9 We can create an object from our class Student as follows. Student s; s = new Student(); The first line declares a variable of type Student. It is called a reference variable and created on stack memory. It behaves like normal variables int x, double y, etc. In the second line, the keyword new creates an object of type Student and assigns its memory location to the reference variable s. Note that the objects are always created on the heap memory. Then modify your Test.java file as follows and again compile & run. Test.java class Test { public static void main(String args[]) { Student s; s=new Student(); System.out.println(s.name); System.out.println(s.age); System.out.println(s.marksMaths); System.out.println(s.marksEnglish); System.out.println(s.average); } } We can use dot operator (.) to access attributes of an object. Following figure shows the output in Command Prompt.
  • 6. Lesson 1 of 4 Object Oriented Programming in Java 6 of 9 We did not assign values to the attributes of the object. Therefore java automatically assigns default values to the attributes. We can use dot operator to assign values to the attributes of an object as well. Then Test.java file is as follows.
  • 7. Lesson 1 of 4 Object Oriented Programming in Java 7 of 9 Test.java class Test { public static void main(String args[]) { Student s; s=new Student(); s.name='A'; s.age=23; marksMaths=67; marksEnglish=84; System.out.println(s.name); System.out.println(s.age); System.out.println(s.marksMaths); System.out.println(s.marksEnglish); System.out.println(s.average); } } Exercise 1. Create following Student objects. We have already created the first one. Object name age marksMaths marksEnglish s ‘A’ 23 67 64 s1 ‘B’ 34 45 88 s2 ‘C’ 22 29 93 s3 ‘D’ 17 74 38 2. Compute the value of the attribute average for each object.
  • 8. Lesson 1 of 4 Object Oriented Programming in Java 8 of 9 Suppose we execute following line of code. s = s1 Now the variable s stores the memory location of the object with the name ‘B’. And the variable s1 also stores the memory location of the object with the name ‘B’. However no variable stores the memory location of the object with the name ‘A’. Therefore the object with the name ‘A’ will be destroyed from the memory. The objects without references are automatically deleted from the memory. The attributes can be divided into two categories. Instance attribute: An instance attribute is an attribute defined in a class for which each object of the class has a separate copy. Class attribute: A class attribute is an attribute defined in a class of which a single copy exists, regardless of how many objects of the class exist. The attributes: name, age, marksMaths, marksEnglish, average are examples for instance attributes. The attribute avg is used to store the average of average marks of each student. There is one avg value for all the students and it should be a class attribute. We use keyword static to distinguish class attributes.
  • 9. Lesson 1 of 4 Object Oriented Programming in Java 9 of 9 Now modify the two files as follows. Student.java class Student { char name; int age; double marksMaths; double marksEnglish; double average; static double avg; } Test.java class Test { public static void main(String args[]) { Student s1=new Student(); Student s2=new Student(); s1.avg=10; System.out.println(s2.avg); } } This will give 10.0 as the output. The avg variable is common to all the objects. Therefore following three lines do the same thing. s1.avg s2.avg Student.avg