SlideShare a Scribd company logo
1 of 49
Class and
Object in Java
1
Classes and Objects in Java
2
Basics of Classes in Java
Objective
In this chapter you will learn:
◎ What classes, objects, methods and instance variables
are.
◎ How to declare a class and use it to create an object.
◎ How to declare methods in a class to implement the
class’s behaviors.
◎ How to declare instance variables in a class to implement
the class’s attributes.
3
Objective Cont.
◎ How to call an object’s method to make that method
perform its task.
◎ The differences between instance variables of a class
and local variables of a method.
◎ How to use a constructor to ensure that an object’s data
is initialized when the object is created.
4
Introduction
◎ Java is a true OO language and therefore the underlying structure of all Java
programs is classes.
◎ Anything we wish to represent in Java must be encapsulated in a class that
defines the “state” and “behaviour” of the basic program components known as
objects.
◎ Classes create objects and objects use methods to communicate between them.
◎ They provide a convenient method for packaging a group of logically related data
items and functions that work on them.
5
Classes
◎ Class − is template/blueprint that describes the
behavior/state that the object of its type support.
6
Circle
centre
radius
circumference()
area()
Classes
◎ A class is a collection of fields (data) and methods (procedure or
function) that operate on that data.
◎ The basic syntax for a class definition:
◎ Bare bone class – no fields, no methods
7
public class Circle {
// my circle class
}
class ClassName [extends
SuperClassName]
{
[fields declaration]
[methods declaration]
}
Adding Fields: Class Circle with fields
◎ Add fields
◎ The fields (data) are also called the instance
varaibles.
8
public class Circle {
public double x, y; // centre coordinate
public double r; // radius of the circle
}
Adding Methods
◎ A class with only data fields has no life. Objects created
by such a class cannot respond to any messages.
◎ Methods are declared inside the body of the class but
immediately after the declaration of data fields.
◎ The general form of a method declaration is:
9
type MethodName (parameter-list)
{
Method-body;
}
Adding Methods to Class Circle
10
public class Circle {
public double x, y; // centre of the circle
public double r; // radius of circle
//Methods to return circumference and area
public double circumference() {
return 2*3.14*r;
}
public double area() {
return 3.14 * r * r;
}
}
Method Body
Multiple class in Java
◎ class A
{
}
◎ class B
{
}
11
class C
{
public static void main(String[] args)
{
System.out.println("Sample output from class C");
}
}
12
Rules Applicable to Source file
◎ There can be only one public class per source code file but
it can have multiple non public classes.
◎ In case there is any public class present in the source code
file, the name of the file should be the name of the class.
◎ Files with no public class can have any name for the class.
13
Rules Cont.
◎ Sequence of statements in a source code file should
be package >> import >> Class declaration.
◎ No Sequence rule is applied for Comments. Comments
can be there in any part of the source code file at any
location.
◎ Import and package statements should be applied to all
the classes in the same source code file.
14
Objects
◎ Object is the physical as well as logical entity
○ a desk, computer, chair, person, etc
◎ An object has a (current) state and behavior.
○ A dog has state (name, color, breed, hungry) and
behavior (barking, fetching, and wagging tail).
15
An Object in Software
 A real world object may be represented in
software.
 Different variables represent the state of the
object.
 Various methods/functions represent the behavior
of the object.
Object Type: Light
Variable: boolean switchState;
Function: void turnSwitch(boolean on) { …. }
 Each object has a type/class.
 An object is an instance of a class/type. We write
new classes to define new types of objects.
 A particular object resembles other objects of its
type. A few variables of an object may be shared
by all objects of the same type.
 An Object can be mutable (has changing state) or
immutable (its methods do not change its state).
 Objects can inherit properties, both state and
behavior, from other objects.
Properties of Objects
Syntax:
<Class_Name> ClassObjectReference = new <Class_Name>();
Example
Circle c1, c2, c3; // They hold a special value called null
// Construct the instances via new operator
c1 = new Circle();
c2 = new Circle(2.0);
c3 = new Circle(3.0, "red");
// You can Declare and Construct in the same statement
Circle c4 = new Circle();
18
Class of Circle cont.
◎ c1, c2 simply refers to a Circle object, not an object
itself.
19
c2
Points to nothing (Null Reference)
c2
Points to nothing (Null Reference)
null null
20
Creating objects of a class
c1 = new Circle();
c2= new Circle() ;
c2= c1;
P
c1
Q
c2
Before Assignment
P
c1
Q
c2
Before Assignment
Automatic garbage collection
◎ The object does not have a reference and
cannot be used in future.
◎ The object becomes a candidate for automatic
garbage collection.
◎ Java automatically collects garbage periodically and
releases the memory used to be used in the future.
21
Q
22
Dot(.) operator
◎ The variables and methods belonging to a
class are formally called member variables
and member methods.
◎ To reference a member variable or method,
you must:
○ First identify the instance you are interested in,
and then,
○ Use the dot operator (.) to reference the desired
member variable or method.
23
Accessing Object/Circle Data
◎ Similar to C syntax for accessing data defined in a
structure.
24
Circle aCircle = new Circle();
aCircle.x = 2.0 // initialize center and radius
aCircle.y = 2.0
aCircle.r = 1.0
ObjectName.VariableName
ObjectName.MethodName(parameter-list)
Executing Methods in Object/Circle
◎ Using Object Methods:
25
Circle aCircle = new Circle();
double area;
aCircle.r = 1.0;
area = aCircle.area();
sent ‘message’ to aCircle
Member Methods
◎ A method (as described in the earlier
chapter):
○ receives arguments from the caller,
○ performs the operations defined in the method
body, and
○ returns a piece of result (or void) to the caller.
26
Using Circle Class
// Circle.java: Contains both Circle class and its user class
//Add Circle class code here
class MyMain
{
public static void main(String args[])
{
Circle aCircle; // creating reference
aCircle = new Circle(); // creating object
aCircle.x = 10; // assigning value to data field
aCircle.y = 20;
aCircle.r = 5;
double area = aCircle.area(); // invoking method
double circumf = aCircle.circumference();
System.out.println("Radius="+aCircle.r+" Area="+area);
System.out.println("Radius="+aCircle.r+" Circumference
="+circumf);
}
}
27 Radius=5.0 Area=78.5
Radius=5.0 Circumference =31.400000000000002
Constructors
◎ A constructor is a special method that has the
same method name as the class name.
◎ A constructor is different from an ordinary method
in the following aspects:
○ The name of the constructor method is the same as
the class name.
○ Constructor has no return type.
○ Constructor can only be invoked via the "new"
operator. Once an instance is constructed, you cannot
call the constructor anymore.
○ Constructors are not inherited
28
Outline of a Class Definition
There is no public static void main() method defined in class Apple.
class Apple {
// Data Fields to record state of Apple.
// Constructor for Making a New Apple.
// Methods for Behavior of Apple.
}
Apple Class – Writing the code.
class Apple {
// Data Fields to record state of Apple.
String color;
// Constructor for Making a New Apple.
Apple(String c) { color = c; }
// Methods for Behavior of Apple.
String getAppleColor() { return color; }
void sliceApple() {
System.out.println(“You sliced this ” + color + “ apple.”);
}
}
Constructors
Class Apple has a constructor:
Apple(String c) {
color = c;
}
 A constructor is a special method that has no return type.
 The constructor name is EXACTLY the same as the class name: Apple
 A constructor constructs a new object using the new keyword:
Apple redApple = new Apple(“red”);
 A constructor must initialize the state of the Apple object. In this
case, the constructor expects a color, then initializes its own color to
the given color specified.
Using the Apple Class
We can use the Apple class now as follows:
We write another class (here, called Application) that includes the
main() method.
class Application {
public static void main(String[] args) {
System.out.println(“Hello World Again !”);
Apple greenApple = new Apple(“green”);
System.out.println(“I made a ” + greenApple.getAppleColor()
+ “ apple, and I am learning objects.”);
}
Using Apple Methods
We can write more statements (using Apple methods) in another
class (for example, the Application class)
What would these statements print out?
Apple redApple = new Apple(“red”);
System.out.println(“We made a ” + redApple.getAppleColor() + “
apple.”);
redApple.sliceApple();
redApple.color = “green”;
System.out.println(“We made a ” + redApple.getAppleColor() + “ apple.”);
LAST TWO LINES INTRODUCE ISSUE OF ACCESS INTO OBJECT.
redApple.color = “green”;
System.out.println(“We made a ” + redApple.getAppleColor() + “ apple?”);
We created a new red apple.
However, we can access the red apple’s color outside the class, and
somehow change it to green. This is obviously not what we want.
Want to limit access:
In the Apple class, we should have written:
private String color; // Now, can’t change color outside Apple class.
Access Into Objects
Private, Public, Nothing Specified.
Private: Can only access variable or method
within the class itself. (Within Apple class)
Public: Can access variable or method everywhere.
(Inside Apple class and Application class)
Nothing Specified: So far, we have not specified any
private or public access. This means
the variable or method is accessible
in the same package (for now, this
means same as public)
Completed Apple Class
public class Apple {
// Data Fields to record state of Apple.
private String color;
// Constructor for Making a New Apple.
public Apple(String c) { color = c; }
// Methods for Behavior of Apple.
public String getAppleColor() { return color; }
public void sliceApple() {
System.out.println(“You sliced this “ + color + “ apple.”);
}
}
redApple.color  can’t write this statement
anymore. The access to the object’s color field
in the Application class is prohibited.
Once we create an apple with a certain color, then it can’t
change.
IF we were writing a leaf class, we might want to have its color
be changeable as the seasons change.
Static Keyword
1. Want all Point Objects to share same Origin.
Point aPoint = new Point();
Point bPoint = new Point();
aPoint.origin is a separate object from bPoint.origin.
SOLUTION: Use static keyword. Now, all Point objects share a
common origin:
aPoint.origin is same object as bPoint.origin.
How does the Static Keyword affect Attributes
◎ When you create a static attribute it “only exists in
the class”. Although each new object has that specific
variable, that variable is only a reference to the same
variable in the class. This means:
○ For all the objects created from that class the static variable
will have the same value in all the objects since they all refer
to the same place in the class
○ If the variables is changed in one of the objects/class this will
change this variable in all objects/class since it really only
exists in one place.
How does the Static Keyword affect Methods
◎ Like static attributes,
static methods only exist in the class.
◎ Static methods cannot refer to non-static variables in the
class.
Final Keyword
2. Want Origin to never change.
Point aPoint = new Point();
aPoint.origin = new Point();
aPoint.origin.x = 0.0;
aPoint.origin = new Point();// Bad – Changes origin
Want to finalize the origin.
SOLUTION: Use final keyword. Now, all Point objects have the same
origin that cannot change.
How does the final Keyword affect attributes and
methods?
◎ It does not let you change the value of a variable after it has
been initialized.
◎ A final variable is a constant.
◎ A final method: prevents someone from overriding the
method in a subclass (discussed in a later lecture).
Revised Point Class
class Point {
double x;
double y;
String label = “node point”;
boolean errorFlag = false;
// Added a totalPoints field for counting objects.
static int totalPoints = 0;
static final Point origin = new Point();
}
Review Example: class Point3D
class Point3D {
double x;
static double y;
static final double z = 7.0;
}
1. Identify class variables (those belonging to all 3DPoint objects)
2. Identify instance variables (those particular to each 3DPoint object)
3. What happens here to p1.x, p2.x, p1.y, p2.y, and p1.z, p2.z
after each statement?
Point3D p1 = new Point3D();
Point3D p2 = new Point3D();
p1.x = 1.0;
p1.y = 2.0;
p2.x = 3.0;
p2.y = 4.0;
Point3D.z = 8.2;
p2.z = 9.9;
Adding Constructors
class Point {
double x, y;
String label = “node point”;
boolean errorFlag = false;
static int totalPoints = 0;
static final Point origin = new Point(0.0, 0.0);
// Construct a new Point – Initialize All empty variables (state).
Point(double xPos, double yPos) {
x = xPos; y = yPos;
++totalPoints;
}
} // End Class Point
Multiple Constructors
class Point {
…
static int totalPoints = 0;
static final Point origin = new Point(0.0, 0.0, “Origin”);
// Construct a new Point given coordinates.
Point(double x, double y) {
this.x = x; this.y = y;
++totalPoints;
}
// Another overloaded constructor using this keyword.
Point(double x, double y, String label) {
this(x, y); //calls alternate constructor
this.label = label;
}
} // End Class Point
this Keyword
 The this keyword is a reference within the class to the
object instance that is being created.
Inside the class Point, the this reference points to the specific Point object
being created.
this.x is the same as using the object’s x parameter unmistakably.
this() would call the default constructor.
this(4.4, 2.8) would call the first constructor.
this.doMethod() would call the object’s method.
public class Point {
// Data Fields
private double x, y;
private String label = “node point”;
private boolean errorFlag = false;
private static int totalPoints = 0;
public static final Point origin =
new Point(0.0, 0.0, “Origin”);
//Constructors
private Point(double x, double y) {}
public Point(double x, double y, String
label) {}
// New Methods
public double getX() {}
public double getY() {}
public String getLabel() {}
public static intgetNumberOfPoints(){}
public double distanceTo(PointpointTwo) {}
} // End Class Point
POINT
+getX()
+getY()
+getNumberOfPoints()
+distanceTo(Point two)
+equals(Object two)
+toString()
x
y
label
totalPoints
errorFlag
origin
Exercise
◎ Define a class book
◎ create objects for the class book
◎ add data fields and methods to
classes
◎ access data fields and methods
to classes
49

More Related Content

Similar to Class and Object.pptx

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
 
Oops concept in c#
Oops concept in c#Oops concept in c#
Oops concept in c#ANURAG SINGH
 
Object Oriented Programming_Lecture 2
Object Oriented Programming_Lecture 2Object Oriented Programming_Lecture 2
Object Oriented Programming_Lecture 2Mahmoud Alfarra
 
Object and class in java
Object and class in javaObject and class in java
Object and class in javaUmamaheshwariv1
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptxarjun431527
 
Lecture-03 _Java Classes_from FAST-NUCES
Lecture-03 _Java Classes_from FAST-NUCESLecture-03 _Java Classes_from FAST-NUCES
Lecture-03 _Java Classes_from FAST-NUCESUzairSaeed18
 
08review (1)
08review (1)08review (1)
08review (1)IIUM
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxchetanpatilcp783
 
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
 
c#(loops,arrays)
c#(loops,arrays)c#(loops,arrays)
c#(loops,arrays)sdrhr
 
Unidad o informatica en ingles
Unidad o informatica en inglesUnidad o informatica en ingles
Unidad o informatica en inglesMarisa Torrecillas
 

Similar to Class and Object.pptx (20)

Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
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
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Oops concept in c#
Oops concept in c#Oops concept in c#
Oops concept in c#
 
Object Oriented Programming_Lecture 2
Object Oriented Programming_Lecture 2Object Oriented Programming_Lecture 2
Object Oriented Programming_Lecture 2
 
Object and class in java
Object and class in javaObject and class in java
Object and class in java
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
 
Lecture-03 _Java Classes_from FAST-NUCES
Lecture-03 _Java Classes_from FAST-NUCESLecture-03 _Java Classes_from FAST-NUCES
Lecture-03 _Java Classes_from FAST-NUCES
 
08review (1)
08review (1)08review (1)
08review (1)
 
Classes1
Classes1Classes1
Classes1
 
Java chapter 4
Java chapter 4Java chapter 4
Java chapter 4
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
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
 
Lecture 4. mte 407
Lecture 4. mte 407Lecture 4. mte 407
Lecture 4. mte 407
 
Java02
Java02Java02
Java02
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
 
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
 
09slide.ppt
09slide.ppt09slide.ppt
09slide.ppt
 
c#(loops,arrays)
c#(loops,arrays)c#(loops,arrays)
c#(loops,arrays)
 
Unidad o informatica en ingles
Unidad o informatica en inglesUnidad o informatica en ingles
Unidad o informatica en ingles
 

More from Hailsh

Lecture_Chapter_7.ppt
Lecture_Chapter_7.pptLecture_Chapter_7.ppt
Lecture_Chapter_7.pptHailsh
 
Lecture_Chapter_8.ppt
Lecture_Chapter_8.pptLecture_Chapter_8.ppt
Lecture_Chapter_8.pptHailsh
 
maintain IT equipment full note.pdf
maintain IT equipment full note.pdfmaintain IT equipment full note.pdf
maintain IT equipment full note.pdfHailsh
 
Bahir dar institute of technology.pdf
Bahir dar institute of technology.pdfBahir dar institute of technology.pdf
Bahir dar institute of technology.pdfHailsh
 
Lac one 01 Parts of computer.pptx
Lac one 01 Parts of computer.pptxLac one 01 Parts of computer.pptx
Lac one 01 Parts of computer.pptxHailsh
 
pracc III for presentation.pptx
pracc III for presentation.pptxpracc III for presentation.pptx
pracc III for presentation.pptxHailsh
 
ACHMT chapter 4 and 5 note.pdf
ACHMT chapter 4 and 5 note.pdfACHMT chapter 4 and 5 note.pdf
ACHMT chapter 4 and 5 note.pdfHailsh
 
Asmamaw CV.docx
Asmamaw CV.docxAsmamaw CV.docx
Asmamaw CV.docxHailsh
 
ManagementschoolsofthoughtbyMSSridhar.pdf
ManagementschoolsofthoughtbyMSSridhar.pdfManagementschoolsofthoughtbyMSSridhar.pdf
ManagementschoolsofthoughtbyMSSridhar.pdfHailsh
 
4_6046473908704512975.pdf
4_6046473908704512975.pdf4_6046473908704512975.pdf
4_6046473908704512975.pdfHailsh
 
4(b) Organizational Theory addisu.pdf
4(b) Organizational Theory  addisu.pdf4(b) Organizational Theory  addisu.pdf
4(b) Organizational Theory addisu.pdfHailsh
 
4(b) Organizational Theory addisu.pdf
4(b) Organizational Theory  addisu.pdf4(b) Organizational Theory  addisu.pdf
4(b) Organizational Theory addisu.pdfHailsh
 
Classroom english.pptx
Classroom english.pptxClassroom english.pptx
Classroom english.pptxHailsh
 
ADDITIONAL READING.pptx
ADDITIONAL READING.pptxADDITIONAL READING.pptx
ADDITIONAL READING.pptxHailsh
 
action research @a.pptx
action research @a.pptxaction research @a.pptx
action research @a.pptxHailsh
 
beshir.pdf
beshir.pdfbeshir.pdf
beshir.pdfHailsh
 
book 11.pptx
book 11.pptxbook 11.pptx
book 11.pptxHailsh
 
book 10.pptx
book 10.pptxbook 10.pptx
book 10.pptxHailsh
 
book 8.pptx
book 8.pptxbook 8.pptx
book 8.pptxHailsh
 
book 7.pptx
book 7.pptxbook 7.pptx
book 7.pptxHailsh
 

More from Hailsh (20)

Lecture_Chapter_7.ppt
Lecture_Chapter_7.pptLecture_Chapter_7.ppt
Lecture_Chapter_7.ppt
 
Lecture_Chapter_8.ppt
Lecture_Chapter_8.pptLecture_Chapter_8.ppt
Lecture_Chapter_8.ppt
 
maintain IT equipment full note.pdf
maintain IT equipment full note.pdfmaintain IT equipment full note.pdf
maintain IT equipment full note.pdf
 
Bahir dar institute of technology.pdf
Bahir dar institute of technology.pdfBahir dar institute of technology.pdf
Bahir dar institute of technology.pdf
 
Lac one 01 Parts of computer.pptx
Lac one 01 Parts of computer.pptxLac one 01 Parts of computer.pptx
Lac one 01 Parts of computer.pptx
 
pracc III for presentation.pptx
pracc III for presentation.pptxpracc III for presentation.pptx
pracc III for presentation.pptx
 
ACHMT chapter 4 and 5 note.pdf
ACHMT chapter 4 and 5 note.pdfACHMT chapter 4 and 5 note.pdf
ACHMT chapter 4 and 5 note.pdf
 
Asmamaw CV.docx
Asmamaw CV.docxAsmamaw CV.docx
Asmamaw CV.docx
 
ManagementschoolsofthoughtbyMSSridhar.pdf
ManagementschoolsofthoughtbyMSSridhar.pdfManagementschoolsofthoughtbyMSSridhar.pdf
ManagementschoolsofthoughtbyMSSridhar.pdf
 
4_6046473908704512975.pdf
4_6046473908704512975.pdf4_6046473908704512975.pdf
4_6046473908704512975.pdf
 
4(b) Organizational Theory addisu.pdf
4(b) Organizational Theory  addisu.pdf4(b) Organizational Theory  addisu.pdf
4(b) Organizational Theory addisu.pdf
 
4(b) Organizational Theory addisu.pdf
4(b) Organizational Theory  addisu.pdf4(b) Organizational Theory  addisu.pdf
4(b) Organizational Theory addisu.pdf
 
Classroom english.pptx
Classroom english.pptxClassroom english.pptx
Classroom english.pptx
 
ADDITIONAL READING.pptx
ADDITIONAL READING.pptxADDITIONAL READING.pptx
ADDITIONAL READING.pptx
 
action research @a.pptx
action research @a.pptxaction research @a.pptx
action research @a.pptx
 
beshir.pdf
beshir.pdfbeshir.pdf
beshir.pdf
 
book 11.pptx
book 11.pptxbook 11.pptx
book 11.pptx
 
book 10.pptx
book 10.pptxbook 10.pptx
book 10.pptx
 
book 8.pptx
book 8.pptxbook 8.pptx
book 8.pptx
 
book 7.pptx
book 7.pptxbook 7.pptx
book 7.pptx
 

Recently uploaded

MAHA Global and IPR: Do Actions Speak Louder Than Words?
MAHA Global and IPR: Do Actions Speak Louder Than Words?MAHA Global and IPR: Do Actions Speak Louder Than Words?
MAHA Global and IPR: Do Actions Speak Louder Than Words?Olivia Kresic
 
Future Of Sample Report 2024 | Redacted Version
Future Of Sample Report 2024 | Redacted VersionFuture Of Sample Report 2024 | Redacted Version
Future Of Sample Report 2024 | Redacted VersionMintel Group
 
Intro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdfIntro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdfpollardmorgan
 
Annual General Meeting Presentation Slides
Annual General Meeting Presentation SlidesAnnual General Meeting Presentation Slides
Annual General Meeting Presentation SlidesKeppelCorporation
 
Global Scenario On Sustainable and Resilient Coconut Industry by Dr. Jelfina...
Global Scenario On Sustainable  and Resilient Coconut Industry by Dr. Jelfina...Global Scenario On Sustainable  and Resilient Coconut Industry by Dr. Jelfina...
Global Scenario On Sustainable and Resilient Coconut Industry by Dr. Jelfina...ictsugar
 
The CMO Survey - Highlights and Insights Report - Spring 2024
The CMO Survey - Highlights and Insights Report - Spring 2024The CMO Survey - Highlights and Insights Report - Spring 2024
The CMO Survey - Highlights and Insights Report - Spring 2024christinemoorman
 
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCRashishs7044
 
8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCR8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCRashishs7044
 
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCRashishs7044
 
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort ServiceCall US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Servicecallgirls2057
 
Independent Call Girls Andheri Nightlaila 9967584737
Independent Call Girls Andheri Nightlaila 9967584737Independent Call Girls Andheri Nightlaila 9967584737
Independent Call Girls Andheri Nightlaila 9967584737Riya Pathan
 
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCRashishs7044
 
Kenya’s Coconut Value Chain by Gatsby Africa
Kenya’s Coconut Value Chain by Gatsby AfricaKenya’s Coconut Value Chain by Gatsby Africa
Kenya’s Coconut Value Chain by Gatsby Africaictsugar
 
Market Sizes Sample Report - 2024 Edition
Market Sizes Sample Report - 2024 EditionMarket Sizes Sample Report - 2024 Edition
Market Sizes Sample Report - 2024 EditionMintel Group
 
Youth Involvement in an Innovative Coconut Value Chain by Mwalimu Menza
Youth Involvement in an Innovative Coconut Value Chain by Mwalimu MenzaYouth Involvement in an Innovative Coconut Value Chain by Mwalimu Menza
Youth Involvement in an Innovative Coconut Value Chain by Mwalimu Menzaictsugar
 
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City GurgaonCall Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaoncallgirls2057
 
2024 Numerator Consumer Study of Cannabis Usage
2024 Numerator Consumer Study of Cannabis Usage2024 Numerator Consumer Study of Cannabis Usage
2024 Numerator Consumer Study of Cannabis UsageNeil Kimberley
 
NewBase 19 April 2024 Energy News issue - 1717 by Khaled Al Awadi.pdf
NewBase  19 April  2024  Energy News issue - 1717 by Khaled Al Awadi.pdfNewBase  19 April  2024  Energy News issue - 1717 by Khaled Al Awadi.pdf
NewBase 19 April 2024 Energy News issue - 1717 by Khaled Al Awadi.pdfKhaled Al Awadi
 

Recently uploaded (20)

MAHA Global and IPR: Do Actions Speak Louder Than Words?
MAHA Global and IPR: Do Actions Speak Louder Than Words?MAHA Global and IPR: Do Actions Speak Louder Than Words?
MAHA Global and IPR: Do Actions Speak Louder Than Words?
 
Future Of Sample Report 2024 | Redacted Version
Future Of Sample Report 2024 | Redacted VersionFuture Of Sample Report 2024 | Redacted Version
Future Of Sample Report 2024 | Redacted Version
 
Intro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdfIntro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdf
 
Corporate Profile 47Billion Information Technology
Corporate Profile 47Billion Information TechnologyCorporate Profile 47Billion Information Technology
Corporate Profile 47Billion Information Technology
 
Annual General Meeting Presentation Slides
Annual General Meeting Presentation SlidesAnnual General Meeting Presentation Slides
Annual General Meeting Presentation Slides
 
Global Scenario On Sustainable and Resilient Coconut Industry by Dr. Jelfina...
Global Scenario On Sustainable  and Resilient Coconut Industry by Dr. Jelfina...Global Scenario On Sustainable  and Resilient Coconut Industry by Dr. Jelfina...
Global Scenario On Sustainable and Resilient Coconut Industry by Dr. Jelfina...
 
The CMO Survey - Highlights and Insights Report - Spring 2024
The CMO Survey - Highlights and Insights Report - Spring 2024The CMO Survey - Highlights and Insights Report - Spring 2024
The CMO Survey - Highlights and Insights Report - Spring 2024
 
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
8447779800, Low rate Call girls in New Ashok Nagar Delhi NCR
 
8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCR8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCR
 
Japan IT Week 2024 Brochure by 47Billion (English)
Japan IT Week 2024 Brochure by 47Billion (English)Japan IT Week 2024 Brochure by 47Billion (English)
Japan IT Week 2024 Brochure by 47Billion (English)
 
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
 
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort ServiceCall US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
 
Independent Call Girls Andheri Nightlaila 9967584737
Independent Call Girls Andheri Nightlaila 9967584737Independent Call Girls Andheri Nightlaila 9967584737
Independent Call Girls Andheri Nightlaila 9967584737
 
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
8447779800, Low rate Call girls in Kotla Mubarakpur Delhi NCR
 
Kenya’s Coconut Value Chain by Gatsby Africa
Kenya’s Coconut Value Chain by Gatsby AfricaKenya’s Coconut Value Chain by Gatsby Africa
Kenya’s Coconut Value Chain by Gatsby Africa
 
Market Sizes Sample Report - 2024 Edition
Market Sizes Sample Report - 2024 EditionMarket Sizes Sample Report - 2024 Edition
Market Sizes Sample Report - 2024 Edition
 
Youth Involvement in an Innovative Coconut Value Chain by Mwalimu Menza
Youth Involvement in an Innovative Coconut Value Chain by Mwalimu MenzaYouth Involvement in an Innovative Coconut Value Chain by Mwalimu Menza
Youth Involvement in an Innovative Coconut Value Chain by Mwalimu Menza
 
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City GurgaonCall Us 📲8800102216📞 Call Girls In DLF City Gurgaon
Call Us 📲8800102216📞 Call Girls In DLF City Gurgaon
 
2024 Numerator Consumer Study of Cannabis Usage
2024 Numerator Consumer Study of Cannabis Usage2024 Numerator Consumer Study of Cannabis Usage
2024 Numerator Consumer Study of Cannabis Usage
 
NewBase 19 April 2024 Energy News issue - 1717 by Khaled Al Awadi.pdf
NewBase  19 April  2024  Energy News issue - 1717 by Khaled Al Awadi.pdfNewBase  19 April  2024  Energy News issue - 1717 by Khaled Al Awadi.pdf
NewBase 19 April 2024 Energy News issue - 1717 by Khaled Al Awadi.pdf
 

Class and Object.pptx

  • 2. Classes and Objects in Java 2 Basics of Classes in Java
  • 3. Objective In this chapter you will learn: ◎ What classes, objects, methods and instance variables are. ◎ How to declare a class and use it to create an object. ◎ How to declare methods in a class to implement the class’s behaviors. ◎ How to declare instance variables in a class to implement the class’s attributes. 3
  • 4. Objective Cont. ◎ How to call an object’s method to make that method perform its task. ◎ The differences between instance variables of a class and local variables of a method. ◎ How to use a constructor to ensure that an object’s data is initialized when the object is created. 4
  • 5. Introduction ◎ Java is a true OO language and therefore the underlying structure of all Java programs is classes. ◎ Anything we wish to represent in Java must be encapsulated in a class that defines the “state” and “behaviour” of the basic program components known as objects. ◎ Classes create objects and objects use methods to communicate between them. ◎ They provide a convenient method for packaging a group of logically related data items and functions that work on them. 5
  • 6. Classes ◎ Class − is template/blueprint that describes the behavior/state that the object of its type support. 6 Circle centre radius circumference() area()
  • 7. Classes ◎ A class is a collection of fields (data) and methods (procedure or function) that operate on that data. ◎ The basic syntax for a class definition: ◎ Bare bone class – no fields, no methods 7 public class Circle { // my circle class } class ClassName [extends SuperClassName] { [fields declaration] [methods declaration] }
  • 8. Adding Fields: Class Circle with fields ◎ Add fields ◎ The fields (data) are also called the instance varaibles. 8 public class Circle { public double x, y; // centre coordinate public double r; // radius of the circle }
  • 9. Adding Methods ◎ A class with only data fields has no life. Objects created by such a class cannot respond to any messages. ◎ Methods are declared inside the body of the class but immediately after the declaration of data fields. ◎ The general form of a method declaration is: 9 type MethodName (parameter-list) { Method-body; }
  • 10. Adding Methods to Class Circle 10 public class Circle { public double x, y; // centre of the circle public double r; // radius of circle //Methods to return circumference and area public double circumference() { return 2*3.14*r; } public double area() { return 3.14 * r * r; } } Method Body
  • 11. Multiple class in Java ◎ class A { } ◎ class B { } 11
  • 12. class C { public static void main(String[] args) { System.out.println("Sample output from class C"); } } 12
  • 13. Rules Applicable to Source file ◎ There can be only one public class per source code file but it can have multiple non public classes. ◎ In case there is any public class present in the source code file, the name of the file should be the name of the class. ◎ Files with no public class can have any name for the class. 13
  • 14. Rules Cont. ◎ Sequence of statements in a source code file should be package >> import >> Class declaration. ◎ No Sequence rule is applied for Comments. Comments can be there in any part of the source code file at any location. ◎ Import and package statements should be applied to all the classes in the same source code file. 14
  • 15. Objects ◎ Object is the physical as well as logical entity ○ a desk, computer, chair, person, etc ◎ An object has a (current) state and behavior. ○ A dog has state (name, color, breed, hungry) and behavior (barking, fetching, and wagging tail). 15
  • 16. An Object in Software  A real world object may be represented in software.  Different variables represent the state of the object.  Various methods/functions represent the behavior of the object. Object Type: Light Variable: boolean switchState; Function: void turnSwitch(boolean on) { …. }
  • 17.  Each object has a type/class.  An object is an instance of a class/type. We write new classes to define new types of objects.  A particular object resembles other objects of its type. A few variables of an object may be shared by all objects of the same type.  An Object can be mutable (has changing state) or immutable (its methods do not change its state).  Objects can inherit properties, both state and behavior, from other objects. Properties of Objects
  • 18. Syntax: <Class_Name> ClassObjectReference = new <Class_Name>(); Example Circle c1, c2, c3; // They hold a special value called null // Construct the instances via new operator c1 = new Circle(); c2 = new Circle(2.0); c3 = new Circle(3.0, "red"); // You can Declare and Construct in the same statement Circle c4 = new Circle(); 18
  • 19. Class of Circle cont. ◎ c1, c2 simply refers to a Circle object, not an object itself. 19 c2 Points to nothing (Null Reference) c2 Points to nothing (Null Reference) null null
  • 20. 20 Creating objects of a class c1 = new Circle(); c2= new Circle() ; c2= c1; P c1 Q c2 Before Assignment P c1 Q c2 Before Assignment
  • 21. Automatic garbage collection ◎ The object does not have a reference and cannot be used in future. ◎ The object becomes a candidate for automatic garbage collection. ◎ Java automatically collects garbage periodically and releases the memory used to be used in the future. 21 Q
  • 22. 22
  • 23. Dot(.) operator ◎ The variables and methods belonging to a class are formally called member variables and member methods. ◎ To reference a member variable or method, you must: ○ First identify the instance you are interested in, and then, ○ Use the dot operator (.) to reference the desired member variable or method. 23
  • 24. Accessing Object/Circle Data ◎ Similar to C syntax for accessing data defined in a structure. 24 Circle aCircle = new Circle(); aCircle.x = 2.0 // initialize center and radius aCircle.y = 2.0 aCircle.r = 1.0 ObjectName.VariableName ObjectName.MethodName(parameter-list)
  • 25. Executing Methods in Object/Circle ◎ Using Object Methods: 25 Circle aCircle = new Circle(); double area; aCircle.r = 1.0; area = aCircle.area(); sent ‘message’ to aCircle
  • 26. Member Methods ◎ A method (as described in the earlier chapter): ○ receives arguments from the caller, ○ performs the operations defined in the method body, and ○ returns a piece of result (or void) to the caller. 26
  • 27. Using Circle Class // Circle.java: Contains both Circle class and its user class //Add Circle class code here class MyMain { public static void main(String args[]) { Circle aCircle; // creating reference aCircle = new Circle(); // creating object aCircle.x = 10; // assigning value to data field aCircle.y = 20; aCircle.r = 5; double area = aCircle.area(); // invoking method double circumf = aCircle.circumference(); System.out.println("Radius="+aCircle.r+" Area="+area); System.out.println("Radius="+aCircle.r+" Circumference ="+circumf); } } 27 Radius=5.0 Area=78.5 Radius=5.0 Circumference =31.400000000000002
  • 28. Constructors ◎ A constructor is a special method that has the same method name as the class name. ◎ A constructor is different from an ordinary method in the following aspects: ○ The name of the constructor method is the same as the class name. ○ Constructor has no return type. ○ Constructor can only be invoked via the "new" operator. Once an instance is constructed, you cannot call the constructor anymore. ○ Constructors are not inherited 28
  • 29. Outline of a Class Definition There is no public static void main() method defined in class Apple. class Apple { // Data Fields to record state of Apple. // Constructor for Making a New Apple. // Methods for Behavior of Apple. }
  • 30. Apple Class – Writing the code. class Apple { // Data Fields to record state of Apple. String color; // Constructor for Making a New Apple. Apple(String c) { color = c; } // Methods for Behavior of Apple. String getAppleColor() { return color; } void sliceApple() { System.out.println(“You sliced this ” + color + “ apple.”); } }
  • 31. Constructors Class Apple has a constructor: Apple(String c) { color = c; }  A constructor is a special method that has no return type.  The constructor name is EXACTLY the same as the class name: Apple  A constructor constructs a new object using the new keyword: Apple redApple = new Apple(“red”);  A constructor must initialize the state of the Apple object. In this case, the constructor expects a color, then initializes its own color to the given color specified.
  • 32. Using the Apple Class We can use the Apple class now as follows: We write another class (here, called Application) that includes the main() method. class Application { public static void main(String[] args) { System.out.println(“Hello World Again !”); Apple greenApple = new Apple(“green”); System.out.println(“I made a ” + greenApple.getAppleColor() + “ apple, and I am learning objects.”); }
  • 33. Using Apple Methods We can write more statements (using Apple methods) in another class (for example, the Application class) What would these statements print out? Apple redApple = new Apple(“red”); System.out.println(“We made a ” + redApple.getAppleColor() + “ apple.”); redApple.sliceApple(); redApple.color = “green”; System.out.println(“We made a ” + redApple.getAppleColor() + “ apple.”); LAST TWO LINES INTRODUCE ISSUE OF ACCESS INTO OBJECT.
  • 34. redApple.color = “green”; System.out.println(“We made a ” + redApple.getAppleColor() + “ apple?”); We created a new red apple. However, we can access the red apple’s color outside the class, and somehow change it to green. This is obviously not what we want. Want to limit access: In the Apple class, we should have written: private String color; // Now, can’t change color outside Apple class. Access Into Objects
  • 35. Private, Public, Nothing Specified. Private: Can only access variable or method within the class itself. (Within Apple class) Public: Can access variable or method everywhere. (Inside Apple class and Application class) Nothing Specified: So far, we have not specified any private or public access. This means the variable or method is accessible in the same package (for now, this means same as public)
  • 36. Completed Apple Class public class Apple { // Data Fields to record state of Apple. private String color; // Constructor for Making a New Apple. public Apple(String c) { color = c; } // Methods for Behavior of Apple. public String getAppleColor() { return color; } public void sliceApple() { System.out.println(“You sliced this “ + color + “ apple.”); } }
  • 37. redApple.color  can’t write this statement anymore. The access to the object’s color field in the Application class is prohibited. Once we create an apple with a certain color, then it can’t change. IF we were writing a leaf class, we might want to have its color be changeable as the seasons change.
  • 38. Static Keyword 1. Want all Point Objects to share same Origin. Point aPoint = new Point(); Point bPoint = new Point(); aPoint.origin is a separate object from bPoint.origin. SOLUTION: Use static keyword. Now, all Point objects share a common origin: aPoint.origin is same object as bPoint.origin.
  • 39. How does the Static Keyword affect Attributes ◎ When you create a static attribute it “only exists in the class”. Although each new object has that specific variable, that variable is only a reference to the same variable in the class. This means: ○ For all the objects created from that class the static variable will have the same value in all the objects since they all refer to the same place in the class ○ If the variables is changed in one of the objects/class this will change this variable in all objects/class since it really only exists in one place.
  • 40. How does the Static Keyword affect Methods ◎ Like static attributes, static methods only exist in the class. ◎ Static methods cannot refer to non-static variables in the class.
  • 41. Final Keyword 2. Want Origin to never change. Point aPoint = new Point(); aPoint.origin = new Point(); aPoint.origin.x = 0.0; aPoint.origin = new Point();// Bad – Changes origin Want to finalize the origin. SOLUTION: Use final keyword. Now, all Point objects have the same origin that cannot change.
  • 42. How does the final Keyword affect attributes and methods? ◎ It does not let you change the value of a variable after it has been initialized. ◎ A final variable is a constant. ◎ A final method: prevents someone from overriding the method in a subclass (discussed in a later lecture).
  • 43. Revised Point Class class Point { double x; double y; String label = “node point”; boolean errorFlag = false; // Added a totalPoints field for counting objects. static int totalPoints = 0; static final Point origin = new Point(); }
  • 44. Review Example: class Point3D class Point3D { double x; static double y; static final double z = 7.0; } 1. Identify class variables (those belonging to all 3DPoint objects) 2. Identify instance variables (those particular to each 3DPoint object) 3. What happens here to p1.x, p2.x, p1.y, p2.y, and p1.z, p2.z after each statement? Point3D p1 = new Point3D(); Point3D p2 = new Point3D(); p1.x = 1.0; p1.y = 2.0; p2.x = 3.0; p2.y = 4.0; Point3D.z = 8.2; p2.z = 9.9;
  • 45. Adding Constructors class Point { double x, y; String label = “node point”; boolean errorFlag = false; static int totalPoints = 0; static final Point origin = new Point(0.0, 0.0); // Construct a new Point – Initialize All empty variables (state). Point(double xPos, double yPos) { x = xPos; y = yPos; ++totalPoints; } } // End Class Point
  • 46. Multiple Constructors class Point { … static int totalPoints = 0; static final Point origin = new Point(0.0, 0.0, “Origin”); // Construct a new Point given coordinates. Point(double x, double y) { this.x = x; this.y = y; ++totalPoints; } // Another overloaded constructor using this keyword. Point(double x, double y, String label) { this(x, y); //calls alternate constructor this.label = label; } } // End Class Point
  • 47. this Keyword  The this keyword is a reference within the class to the object instance that is being created. Inside the class Point, the this reference points to the specific Point object being created. this.x is the same as using the object’s x parameter unmistakably. this() would call the default constructor. this(4.4, 2.8) would call the first constructor. this.doMethod() would call the object’s method.
  • 48. public class Point { // Data Fields private double x, y; private String label = “node point”; private boolean errorFlag = false; private static int totalPoints = 0; public static final Point origin = new Point(0.0, 0.0, “Origin”); //Constructors private Point(double x, double y) {} public Point(double x, double y, String label) {} // New Methods public double getX() {} public double getY() {} public String getLabel() {} public static intgetNumberOfPoints(){} public double distanceTo(PointpointTwo) {} } // End Class Point POINT +getX() +getY() +getNumberOfPoints() +distanceTo(Point two) +equals(Object two) +toString() x y label totalPoints errorFlag origin
  • 49. Exercise ◎ Define a class book ◎ create objects for the class book ◎ add data fields and methods to classes ◎ access data fields and methods to classes 49