SlideShare uma empresa Scribd logo
1 de 14
Baixar para ler offline
Spotle.ai Study Material
Spotle.ai/Learn
Class And Object
in Java
Spotle.ai Study Material
Spotle.ai/Learn
A class is a data type in Java that
defines a template or blueprint for
an object. In other words a class
refers to the category or type of
objects. So your cat Kitty is of
type cat, your red Mercedes is of
type car and your bank account is
of type savings account. A class
has variables defining properties
and methods defining behaviour
of its objects.
Class
Image Source: Wikipedia
2
Spotle.ai Study Material
Spotle.ai/Learn
Class Syntax
3
Public Class Cat
{
colour;
breed;
getBreed()
meow()
eat()
}
Variables
Methods
Name of
the class
Spotle.ai Study Material
Spotle.ai/Learn
A variable is a named
field containing
information associated
with the class or object.
For example the colour
variable of Class Cat
indicates the colour of
the specific cat. A
variable has a data type
indicating what type of
variable (number, text,
array, custom, etc) it is.
What Are Variables?
4
Colour
= Black
Colour
= White
Spotle.ai Study Material
Spotle.ai/Learn
Types Of Variables
5
Local
Variables
• A variable declared inside
a class method/
constructor is called a
local variable.
• Other methods in the
class are not aware of
these variables.
• For example, consider the
drink method of class Cat:
drink()
{float milk_qty = 10}
milk_qty is a local
variable of method
drink().
Instance
Variables
• Are variables declared
inside a class but outside
of any method or
constructor.
• These are called instance
variables because their
values are instance
specific and are not
shared among instances.
Eg. the colour variable of
the Class Cat.
Class
Variables
• Are variables declared
inside a class with the
keyword static.
• A single copy of a static
variable is shared among
all instances of a class.
• Static variables are used
to declare common
properties – for example
the number of legs of a
cat or the mileage of a
brand of cars.
Spotle.ai Study Material
Spotle.ai/Learn
What Is A Class?
6
What is your
colour?
But you cannothide your
no_of_legs. Thatis a static variablein Class Cat!
Instance And Static Variables
My colour is my
colour. None of
your colour!
Spotle.ai Study Material
Spotle.ai/Learn
Methods are used to describe
behaviour of the objects of a class.
A method is a set of statements
which is referred to by name and
can be invoked at any point in a
program. It performs a logical unit
of work.
For example get_mileage() method
in class Car is used to return a
specific car’s mileage. In our cat
example, meow() and drink_milk
are methods of the cat objects.
What Are Methods?
7
Meow()
Meow()
Spotle.ai Study Material
Spotle.ai/Learn
Public int getMileage()
{
return mileage;
}
Public void refuel(float fuel)
{
total_fuel = total_fuel + fuel;
}
Syntax Of A Method
8
Return type indicates
the data type of the
variable returned by a
method.
This indicates the
parameter with which
the method is invoked
from within a program.
This is the method
name.
The body of the
method describes the
functionality.
Spotle.ai Study Material
Spotle.ai/Learn
What Are Constructors?
9
Constructor is a block of code defined
in a class that initializes the newly
created object.
A constructor is structurally very
similar to an instance method in Java
but it is not a method as it doesn’t
have a return type.
A constructor is automatically called
when the instance of a class is
created.
Public class Cat
{
Cat()
{
System.out.println(“Meow !I
am a new Cat.”)
}
}
Definition Example
Spotle.ai Study Material
Spotle.ai/Learn
Types Of Constructors
10
If a class does not have
any constructor, Java
compiler inserts a default
constructor into the code.
A default constructor, for
class Cat, looks like this.
Note the body is empty:
Cat()
{
}
The default constructor is
not inserted if you
implement a constructor
for your class.
A no-argument
constructor is one that
takes no arguments or
parameters.
For example:
Cat()
{
System.out.println(“Meow
!I am a new Cat.”)
}
}
Default
Constructors
Parameterized
Constructors
No Argument
Constructors
A constructor with
arguments or parameters
is known as a
Parameterized
constructor.
For example:
Cat( String msg)
{
System.out.println(“Meow
!I am a new Cat with a
special message” + msg)
}
}
Spotle.ai Study Material
Spotle.ai/Learn
Class Syntax - Revisited
11
public class Cat
{
string colour;
string breed;
static no_of_legs = 4
Cat()
{
System.out.println(“Meow !I
I am a new Cat.”)
}
public void meow()
{
System.out.println(“Meow on demand!”);
}
}
Variables
Methods
Name of
the class
Constructors
Spotle.ai Study Material
Spotle.ai/Learn
What Is An Object?
Think of the class like the Mercedes blue-print
and the object like your brand new Mercedes.
12
Object is an instance of a class.
An object is a self-contained
component with methods or
behaviour and properties or state.
Objects are the real world
manifestation of a class like your
house is the manifestation of the
architect’s blue-print. Or your car is a
real object of type car.
Objects occupy memory location at
run-time.
Spotle.ai Study Material
Spotle.ai/Learn
Creating An Object In Java
13
Cat myKitty = new Cat()
Cat myKitty is the declaration of the
object myKitty of class Cat.
Objects are created by using the
operator New which allocates memory
for the object.
The Cat() command invokes the no-arg
constructor we defined earlier (In Slide
11).
So when Cat myKitty = new Cat()
is run, the following gets printed:
Meow! I am a new Cat.
Spotle.ai Study Material
Spotle.ai/Learn
Class Object
A class is a data type.
It defines a template
or blueprint for an
object.
Object is an instance
of a class.
Does not occupy
memory location.
Occupies memory
location at run time.
Does not really exist
as it only provides a
template. You can
therefore not perform
operations on a class.
You perform
operations on objects.
Class Vs Object
14
Think of the class like the Mercedes blue-print
and the object like your brand new Mercedes.

Mais conteúdo relacionado

Mais procurados

Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 

Mais procurados (20)

Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
 
Java swing
Java swingJava swing
Java swing
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Applets in java
Applets in javaApplets in java
Applets in java
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and Operators
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
 
Inheritance and Polymorphism
Inheritance and PolymorphismInheritance and Polymorphism
Inheritance and Polymorphism
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 

Semelhante a Class and Objects in Java

Is2215 lecture2 student(2)
Is2215 lecture2 student(2)Is2215 lecture2 student(2)
Is2215 lecture2 student(2)
dannygriff1
 

Semelhante a Class and Objects in Java (20)

Lecture 4
Lecture 4Lecture 4
Lecture 4
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
Classes_python.pptx
Classes_python.pptxClasses_python.pptx
Classes_python.pptx
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Java is an Object-Oriented Language
Java is an Object-Oriented LanguageJava is an Object-Oriented Language
Java is an Object-Oriented Language
 
java
javajava
java
 
07slide.ppt
07slide.ppt07slide.ppt
07slide.ppt
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
Is2215 lecture2 student(2)
Is2215 lecture2 student(2)Is2215 lecture2 student(2)
Is2215 lecture2 student(2)
 
python note.pdf
python note.pdfpython note.pdf
python note.pdf
 
Ground Gurus - Python Code Camp - Day 3 - Classes
Ground Gurus - Python Code Camp - Day 3 - ClassesGround Gurus - Python Code Camp - Day 3 - Classes
Ground Gurus - Python Code Camp - Day 3 - Classes
 
Unidad o informatica en ingles
Unidad o informatica en inglesUnidad o informatica en ingles
Unidad o informatica en ingles
 
S12.s01 - Material TP.pdf
S12.s01 - Material TP.pdfS12.s01 - Material TP.pdf
S12.s01 - Material TP.pdf
 
Unit - 3.pptx
Unit - 3.pptxUnit - 3.pptx
Unit - 3.pptx
 
JS-02-JavaScript-Objects.ppt
JS-02-JavaScript-Objects.pptJS-02-JavaScript-Objects.ppt
JS-02-JavaScript-Objects.ppt
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
IPP-M5-C1-Classes _ Objects python -S2.pptx
IPP-M5-C1-Classes _ Objects python -S2.pptxIPP-M5-C1-Classes _ Objects python -S2.pptx
IPP-M5-C1-Classes _ Objects python -S2.pptx
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptx
 
Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ Comparator
 

Mais de Spotle.ai

Mais de Spotle.ai (20)

Spotle AI-thon - AI For Good Business Plan Showcase - Team IIM Indore - AI Ro...
Spotle AI-thon - AI For Good Business Plan Showcase - Team IIM Indore - AI Ro...Spotle AI-thon - AI For Good Business Plan Showcase - Team IIM Indore - AI Ro...
Spotle AI-thon - AI For Good Business Plan Showcase - Team IIM Indore - AI Ro...
 
Spotle AI-thon - AI For Good Business Plan Showcase - Cummins College
Spotle AI-thon - AI For Good Business Plan Showcase - Cummins CollegeSpotle AI-thon - AI For Good Business Plan Showcase - Cummins College
Spotle AI-thon - AI For Good Business Plan Showcase - Cummins College
 
Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Team Elit...
Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Team Elit...Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Team Elit...
Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Team Elit...
 
Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India- Ankur chat...
Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India- Ankur chat...Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India- Ankur chat...
Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India- Ankur chat...
 
Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Team La c...
Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Team La c...Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Team La c...
Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Team La c...
 
Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Team Temp...
Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Team Temp...Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Team Temp...
Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Team Temp...
 
Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Team Zer...
 Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Team Zer... Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Team Zer...
Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Team Zer...
 
Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Shivam Gi...
Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Shivam Gi...Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Shivam Gi...
Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Shivam Gi...
 
Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Cyber Pun...
Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Cyber Pun...Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Cyber Pun...
Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Cyber Pun...
 
Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Tech Owls...
Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Tech Owls...Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Tech Owls...
Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Tech Owls...
 
Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Team Jar...
 Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Team Jar... Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Team Jar...
Spotle AI-thon Top 10 Showcase - Analysing Mental Health Of India - Team Jar...
 
Artificial intelligence in fintech
Artificial intelligence in fintechArtificial intelligence in fintech
Artificial intelligence in fintech
 
Semi-supervised Machine Learning
Semi-supervised Machine LearningSemi-supervised Machine Learning
Semi-supervised Machine Learning
 
Basics of Reinforcement Learning
Basics of Reinforcement LearningBasics of Reinforcement Learning
Basics of Reinforcement Learning
 
Tableau And Data Visualization - Get Started
Tableau And Data Visualization - Get StartedTableau And Data Visualization - Get Started
Tableau And Data Visualization - Get Started
 
Artificial Intelligence in FinTech
Artificial Intelligence in FinTechArtificial Intelligence in FinTech
Artificial Intelligence in FinTech
 
Supervised and Unsupervised Machine Learning
Supervised and Unsupervised Machine LearningSupervised and Unsupervised Machine Learning
Supervised and Unsupervised Machine Learning
 
Growing-up With AI
Growing-up With AIGrowing-up With AI
Growing-up With AI
 
AI And Cyber-security Threats
AI And Cyber-security ThreatsAI And Cyber-security Threats
AI And Cyber-security Threats
 
Robotic Process Automation With Blue Prism
Robotic Process Automation With Blue PrismRobotic Process Automation With Blue Prism
Robotic Process Automation With Blue Prism
 

Último

The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 

Último (20)

MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodology
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
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-...
 
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
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.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...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 

Class and Objects in Java

  • 2. Spotle.ai Study Material Spotle.ai/Learn A class is a data type in Java that defines a template or blueprint for an object. In other words a class refers to the category or type of objects. So your cat Kitty is of type cat, your red Mercedes is of type car and your bank account is of type savings account. A class has variables defining properties and methods defining behaviour of its objects. Class Image Source: Wikipedia 2
  • 3. Spotle.ai Study Material Spotle.ai/Learn Class Syntax 3 Public Class Cat { colour; breed; getBreed() meow() eat() } Variables Methods Name of the class
  • 4. Spotle.ai Study Material Spotle.ai/Learn A variable is a named field containing information associated with the class or object. For example the colour variable of Class Cat indicates the colour of the specific cat. A variable has a data type indicating what type of variable (number, text, array, custom, etc) it is. What Are Variables? 4 Colour = Black Colour = White
  • 5. Spotle.ai Study Material Spotle.ai/Learn Types Of Variables 5 Local Variables • A variable declared inside a class method/ constructor is called a local variable. • Other methods in the class are not aware of these variables. • For example, consider the drink method of class Cat: drink() {float milk_qty = 10} milk_qty is a local variable of method drink(). Instance Variables • Are variables declared inside a class but outside of any method or constructor. • These are called instance variables because their values are instance specific and are not shared among instances. Eg. the colour variable of the Class Cat. Class Variables • Are variables declared inside a class with the keyword static. • A single copy of a static variable is shared among all instances of a class. • Static variables are used to declare common properties – for example the number of legs of a cat or the mileage of a brand of cars.
  • 6. Spotle.ai Study Material Spotle.ai/Learn What Is A Class? 6 What is your colour? But you cannothide your no_of_legs. Thatis a static variablein Class Cat! Instance And Static Variables My colour is my colour. None of your colour!
  • 7. Spotle.ai Study Material Spotle.ai/Learn Methods are used to describe behaviour of the objects of a class. A method is a set of statements which is referred to by name and can be invoked at any point in a program. It performs a logical unit of work. For example get_mileage() method in class Car is used to return a specific car’s mileage. In our cat example, meow() and drink_milk are methods of the cat objects. What Are Methods? 7 Meow() Meow()
  • 8. Spotle.ai Study Material Spotle.ai/Learn Public int getMileage() { return mileage; } Public void refuel(float fuel) { total_fuel = total_fuel + fuel; } Syntax Of A Method 8 Return type indicates the data type of the variable returned by a method. This indicates the parameter with which the method is invoked from within a program. This is the method name. The body of the method describes the functionality.
  • 9. Spotle.ai Study Material Spotle.ai/Learn What Are Constructors? 9 Constructor is a block of code defined in a class that initializes the newly created object. A constructor is structurally very similar to an instance method in Java but it is not a method as it doesn’t have a return type. A constructor is automatically called when the instance of a class is created. Public class Cat { Cat() { System.out.println(“Meow !I am a new Cat.”) } } Definition Example
  • 10. Spotle.ai Study Material Spotle.ai/Learn Types Of Constructors 10 If a class does not have any constructor, Java compiler inserts a default constructor into the code. A default constructor, for class Cat, looks like this. Note the body is empty: Cat() { } The default constructor is not inserted if you implement a constructor for your class. A no-argument constructor is one that takes no arguments or parameters. For example: Cat() { System.out.println(“Meow !I am a new Cat.”) } } Default Constructors Parameterized Constructors No Argument Constructors A constructor with arguments or parameters is known as a Parameterized constructor. For example: Cat( String msg) { System.out.println(“Meow !I am a new Cat with a special message” + msg) } }
  • 11. Spotle.ai Study Material Spotle.ai/Learn Class Syntax - Revisited 11 public class Cat { string colour; string breed; static no_of_legs = 4 Cat() { System.out.println(“Meow !I I am a new Cat.”) } public void meow() { System.out.println(“Meow on demand!”); } } Variables Methods Name of the class Constructors
  • 12. Spotle.ai Study Material Spotle.ai/Learn What Is An Object? Think of the class like the Mercedes blue-print and the object like your brand new Mercedes. 12 Object is an instance of a class. An object is a self-contained component with methods or behaviour and properties or state. Objects are the real world manifestation of a class like your house is the manifestation of the architect’s blue-print. Or your car is a real object of type car. Objects occupy memory location at run-time.
  • 13. Spotle.ai Study Material Spotle.ai/Learn Creating An Object In Java 13 Cat myKitty = new Cat() Cat myKitty is the declaration of the object myKitty of class Cat. Objects are created by using the operator New which allocates memory for the object. The Cat() command invokes the no-arg constructor we defined earlier (In Slide 11). So when Cat myKitty = new Cat() is run, the following gets printed: Meow! I am a new Cat.
  • 14. Spotle.ai Study Material Spotle.ai/Learn Class Object A class is a data type. It defines a template or blueprint for an object. Object is an instance of a class. Does not occupy memory location. Occupies memory location at run time. Does not really exist as it only provides a template. You can therefore not perform operations on a class. You perform operations on objects. Class Vs Object 14 Think of the class like the Mercedes blue-print and the object like your brand new Mercedes.