SlideShare a Scribd company logo
OBJECTS
AND
CLASSES
Opening the World of Potential
Java programs are made of objects that interact
with each other
◦ Each object is based on a class
◦ A class describes a set of objects with the same behavior
Each class defines a specific set of methods to use
with its objects
◦ For example, the String class provides methods:
◦ Examples: length() and charAt() methods
String greeting = “Hello World”;
int len = greeting.length();
char c1 = greeting.charAt(0);
Diagram of a Class
Private Data
◦ Each object has its own private data
that other objects cannot directly
access
◦ Methods of the public interface
provide access to private data, while
hiding implementation details:
◦ This is called Encapsulation
Public Interface
◦ Each object has a set of methods
available for other objects to use
Class
Private Data
(Variables)
Public Interface
(Methods)
Public Interface of a Class
Why do you need a class?
◦ What tasks will this class perform?
◦ What methods will you need?
◦ What parameters will the methods need to receive?
◦ What will the methods return?
Task Method Returns
Add the price of an item addItem(double) void
Get the total amount owed getTotal() double
Get the count of items purchased getCount() int
Clear the cash register for a new sale clear() void
To create a Class
You need:
◦ Public class name
◦ Private instance variables
◦ Constructors
◦ Getters & Setters
◦ Helper methods
Classes – Instance Variables
Each object instantiated from the class has its own set of
instance variables
◦ Instance variables describe the class
◦ They store the state of the object
Defining instance variables:
◦ Access Specifiers
◦ Classes (and interface methods) are public
◦ Instance variables are always private
◦ DataType
◦ Instance Variable name – EXTREMELY IMPORTANT TO USE CAMEL
CASING
public class Animal
private String type;
private String name;
private double weight;
private int age;
Private access modifiers mean the variable is
only accessible within the class.
Accessing Instance Variables
public static void main(String[] args)
{
. . .
System.out.println( cat.age ); // Error
. . .
}
The compiler will not allow
this violation of privacy
 Use accessor methods of the class instead!
public static void main(String[] args)
{
. . .
System.out.println( cat.getAge() ); // OK
. . .
}
Encapsulation provides a public interface
and hides the implementation details.
Accessor and Mutator Methods
1) Accessor Methods: 'get' methods
◦ Asks the object for information without changing it
◦ Normally return a value of some type
2) Mutator Methods: 'set' methods
◦ Changes values in the object
◦ Usually take a parameter that will change an instance variable
◦ Normally return void
public void addItem(double price) { }
public void clear() { }
public double getTotal() { }
public int getCount() { }
Constructors
A constructor is a method that initializes instance
variables of an object
◦ It is automatically called when an object is created
◦ It has exactly the same name as the class
public class Animal
{
. . .
public Animal() // A default no-arg constructor
{
}
}
Constructors never return values, but
do not use void in their declaration
POJO Characteristics
All POJOs MUST HAVE A DEFAULT NO-ARG CONSTRUCTOR
◦ (yes, I‘m yelling about it!)
Either implicit or explicit
◦ Implicit – assumes one but not specifically defined
◦ Explicit – if you have a non-default constructor, you must
add in a default no-arg constructor
The Default Constructor
If you do not supply any constructors, the compiler will
make a default constructor automatically
◦ It takes no parameters
◦ It initializes all instance variables
public class Animal
{
. . .
/**
Does exactly what a compiler generated constructor would do.
*/
public Animal()
{
//all instance variables would be set to a default value
}
}
By default, numbers are initialized to 0,
booleans to false, and objects as null.
Multiple Constructors
A class can have more than one constructor
◦ Each must have a unique set of parameters
public class Animal
{
. . .
/**
Constructs an animal with no features */
public Animal( ) { . . . } // default no-arg constructor
/**
Constructs an animal with a type
@param type the type of animal
*/
public Animal(String type) { . . . } // a non-default constructor
}
The compiler picks the constructor that
matches the construction parameters.
Common Error – Declaring a Constructor as void
◦ Constructors have no return type
◦ This creates a method with a return type of void which is NOT a
constructor!
◦ The Java compiler does not consider this an error
public class Animal
{
/**
Intended to be a constructor.
*/
public void Animal( )
{
. . .
}
}
Not a constructor…. Just another
method that returns nothing (void)
Constructors are defined in the class.
public class Animal
Constructors are used to create the objects in another class.
public class AnimalTester
public static void main(String[] args)
Overloading Constructors
◦ Multiple constructors can have exactly the same name
◦ They require different lists of parameters
◦ Actually any method can be overloaded
◦ Same method name with different parameters
public Animal() { . . . }
public Animal(String type) { . . . }
public Animal(String type, String name) { . . . }
public Animal(String type, String name, int age) { . . . }
public Animal(String name) { . . . }
Helper Methods
toString( ) to see what is inside the instance variables
Other methods needed to use the class
haveBirthday( ) to add another year to the age
loseWeight(double weightLoss) to remove pounds
gainWeight(double weightGain) to add more pounds
Constructor this reference
Use the this reference in constructors
◦ It makes it very clear that you are setting the instance variable:
public class Animal
{
private String name;
public Animal(String name)
{
this.name = name;
}
}
public class AnimalTester
{
public static void main(String[] args)
{
Animal dog = new Animal();
...
Testing a Class
We wrote an Animal class but…
◦ You cannot execute the class – it has no main method
It can become part of a larger program
◦ Test it first though with unit testing
To test a new class, you can use:
◦ Junit
◦ Or write a tester class:
◦ With a main
Instantiating Objects
Objects are created based on classes
◦ Use the new operator to construct objects
◦ Give each object a unique name (like variables)
You have used the new operator before:
These do NOT go into the class definition file!
Scanner in = new Scanner(System.in);
Separating the View and
Model
Scanners go in the main method
No sysouts in the classes – except for testing. Comment them out
before submission.
✔ MVC View Pattern – Model View Controller
Use the new operator to
construct objects of a class.
Animal penguin = new Animal();
Animal cat = new Animal();
Object nameClass name Class name
Creating two instances of Animals objects
AnimalTester.java
Add a main method
public class AnimalTester {
public static void main(String[] args) {
Animal dog = new Animal();
dog.setType(“Dog”);
sysout(dog.toString( ));
Animal tiger = new Animal(“Tiger”);
sysout(tiger.toString( ));
Name Bark Leaves
Leaf Size
in cm
Fruit
Zone of
Tree
Hardiness
Hackberry flaky
3 veins
at base 9 TRUE 6
Red oak smooth
matte,
variable 20 FALSE 3
English
Walnut
smooth
plates
between
fissures leaflets 45 TRUE 8
Name Bark Leaves
Leaf Size
in cm
Fruit
Zone of
Tree
Hardiness
Hackberry flaky
3 veins
at base 9 TRUE 6
Red oak smooth
matte,
variable 20 FALSE 3
English
Walnut
smooth
plates
between
fissures leaflets 45 TRUE 8

More Related Content

PPTX
Logic and Coding of Java Interfaces & Swing Applications
kjkleindorfer
 
PPTX
Week10 packages using objects in objects
kjkleindorfer
 
PDF
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute
 
PPTX
Pi j3.2 polymorphism
mcollison
 
PPT
Classes&objects
M Vishnuvardhan Reddy
 
PPTX
Java class,object,method introduction
Sohanur63
 
PPTX
Class introduction in java
yugandhar vadlamudi
 
PDF
Lect 1-java object-classes
Fajar Baskoro
 
Logic and Coding of Java Interfaces & Swing Applications
kjkleindorfer
 
Week10 packages using objects in objects
kjkleindorfer
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute
 
Pi j3.2 polymorphism
mcollison
 
Classes&objects
M Vishnuvardhan Reddy
 
Java class,object,method introduction
Sohanur63
 
Class introduction in java
yugandhar vadlamudi
 
Lect 1-java object-classes
Fajar Baskoro
 

What's hot (20)

PPT
Object and Classes in Java
backdoor
 
PDF
Classes and objects in java
Muthukumaran Subramanian
 
PPT
Java: Objects and Object References
Tareq Hasan
 
PDF
CLASS & OBJECT IN JAVA
Riaj Uddin Mahi
 
PDF
Java Methods
Rosmina Joy Cabauatan
 
PPTX
Static keyword ppt
Vinod Kumar
 
PDF
ITFT-Classes and object in java
Atul Sehdev
 
PPTX
Classes, objects in JAVA
Abhilash Nair
 
PPT
Lect 1-class and object
Fajar Baskoro
 
PPS
Introduction to class in java
kamal kotecha
 
PPTX
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
DevaKumari Vijay
 
PPT
11 Using classes and objects
maznabili
 
PPTX
Object oriented programming in java
Elizabeth alexander
 
PDF
Python Class | Python Programming | Python Tutorial | Edureka
Edureka!
 
PPTX
Unit3 part1-class
DevaKumari Vijay
 
PPT
Object and class
mohit tripathi
 
PPTX
Unit3 part3-packages and interfaces
DevaKumari Vijay
 
PDF
Class and Objects in Java
Spotle.ai
 
PPTX
Classes and objects
Shailendra Veeru
 
Object and Classes in Java
backdoor
 
Classes and objects in java
Muthukumaran Subramanian
 
Java: Objects and Object References
Tareq Hasan
 
CLASS & OBJECT IN JAVA
Riaj Uddin Mahi
 
Java Methods
Rosmina Joy Cabauatan
 
Static keyword ppt
Vinod Kumar
 
ITFT-Classes and object in java
Atul Sehdev
 
Classes, objects in JAVA
Abhilash Nair
 
Lect 1-class and object
Fajar Baskoro
 
Introduction to class in java
kamal kotecha
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
DevaKumari Vijay
 
11 Using classes and objects
maznabili
 
Object oriented programming in java
Elizabeth alexander
 
Python Class | Python Programming | Python Tutorial | Edureka
Edureka!
 
Unit3 part1-class
DevaKumari Vijay
 
Object and class
mohit tripathi
 
Unit3 part3-packages and interfaces
DevaKumari Vijay
 
Class and Objects in Java
Spotle.ai
 
Classes and objects
Shailendra Veeru
 
Ad

Similar to Week9 Intro to classes and objects in Java (20)

PPTX
Lecture 4
talha ijaz
 
PPTX
Computer programming 2 Lesson 3
MLG College of Learning, Inc
 
PDF
CS8392-OOPS-Printed-Notes-All-Units.pdf for students
KaviShetty
 
PPTX
Lecture 5
talha ijaz
 
PDF
Basic java for Android Developer
Nattapong Tonprasert
 
PPT
Defining classes-and-objects-1.0
BG Java EE Course
 
PPT
Internet programming slide - java.ppt
MikeAdva
 
PPTX
Ch-2ppt.pptx
ssuser8347a1
 
PPTX
classes-objects in oops java-201023154255.pptx
janetvidyaanancys
 
PPTX
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
İbrahim Kürce
 
PPTX
introduction_OOP for the java courses [Autosaved].pptx
DrShamimAlMamun
 
PPTX
Classes objects in java
Madishetty Prathibha
 
PDF
LECTURE 4 CLASSES AND OBJECTS.pdf
ShashikantSathe3
 
PDF
Core Java Introduction | Basics
Hùng Nguyễn Huy
 
PPTX
UNIT 3- Java- Inheritance, Multithreading.pptx
shilpar780389
 
PPT
Java Presentation.ppt
Morgan309846
 
PDF
Lecture 1 - Objects and classes
Syed Afaq Shah MACS CP
 
PPTX
Java Classes fact general wireless-19*5.pptx
IbrahimMerzayiee
 
PDF
Classes and objects
Kasun Ranga Wijeweera
 
Lecture 4
talha ijaz
 
Computer programming 2 Lesson 3
MLG College of Learning, Inc
 
CS8392-OOPS-Printed-Notes-All-Units.pdf for students
KaviShetty
 
Lecture 5
talha ijaz
 
Basic java for Android Developer
Nattapong Tonprasert
 
Defining classes-and-objects-1.0
BG Java EE Course
 
Internet programming slide - java.ppt
MikeAdva
 
Ch-2ppt.pptx
ssuser8347a1
 
classes-objects in oops java-201023154255.pptx
janetvidyaanancys
 
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
İbrahim Kürce
 
introduction_OOP for the java courses [Autosaved].pptx
DrShamimAlMamun
 
Classes objects in java
Madishetty Prathibha
 
LECTURE 4 CLASSES AND OBJECTS.pdf
ShashikantSathe3
 
Core Java Introduction | Basics
Hùng Nguyễn Huy
 
UNIT 3- Java- Inheritance, Multithreading.pptx
shilpar780389
 
Java Presentation.ppt
Morgan309846
 
Lecture 1 - Objects and classes
Syed Afaq Shah MACS CP
 
Java Classes fact general wireless-19*5.pptx
IbrahimMerzayiee
 
Classes and objects
Kasun Ranga Wijeweera
 
Ad

More from kjkleindorfer (8)

PPTX
Week11 Inheritance class relationships in Java
kjkleindorfer
 
PPTX
Intro to Bootstrap
kjkleindorfer
 
PPTX
Layouts Part 2
kjkleindorfer
 
PPTX
Layouts
kjkleindorfer
 
PPTX
Using PHP to submit forms
kjkleindorfer
 
PPTX
Forms Part 1
kjkleindorfer
 
PPTX
CSS Box Model
kjkleindorfer
 
PPTX
CSS Selectors and Fonts
kjkleindorfer
 
Week11 Inheritance class relationships in Java
kjkleindorfer
 
Intro to Bootstrap
kjkleindorfer
 
Layouts Part 2
kjkleindorfer
 
Layouts
kjkleindorfer
 
Using PHP to submit forms
kjkleindorfer
 
Forms Part 1
kjkleindorfer
 
CSS Box Model
kjkleindorfer
 
CSS Selectors and Fonts
kjkleindorfer
 

Recently uploaded (20)

PPTX
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
PPTX
Congenital Hypothyroidism pptx
AneetaSharma15
 
PPTX
vedic maths in python:unleasing ancient wisdom with modern code
mistrymuskan14
 
PDF
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
PPTX
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
PDF
Exploring-Forces 5.pdf/8th science curiosity/by sandeep swamy notes/ppt
Sandeep Swamy
 
PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
PDF
Sunset Boulevard Student Revision Booklet
jpinnuck
 
PDF
7.Particulate-Nature-of-Matter.ppt/8th class science curiosity/by k sandeep s...
Sandeep Swamy
 
PPTX
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
PDF
Arihant Class 10 All in One Maths full pdf
sajal kumar
 
PPTX
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
PDF
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
PPTX
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
PPTX
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
PDF
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
PPTX
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
PDF
Types of Literary Text: Poetry and Prose
kaelandreabibit
 
PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
MartinaBurlando1
 
PPTX
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
Congenital Hypothyroidism pptx
AneetaSharma15
 
vedic maths in python:unleasing ancient wisdom with modern code
mistrymuskan14
 
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
Exploring-Forces 5.pdf/8th science curiosity/by sandeep swamy notes/ppt
Sandeep Swamy
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
Sunset Boulevard Student Revision Booklet
jpinnuck
 
7.Particulate-Nature-of-Matter.ppt/8th class science curiosity/by k sandeep s...
Sandeep Swamy
 
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
Arihant Class 10 All in One Maths full pdf
sajal kumar
 
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
Types of Literary Text: Poetry and Prose
kaelandreabibit
 
NOI Hackathon - Summer Edition - GreenThumber.pptx
MartinaBurlando1
 
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 

Week9 Intro to classes and objects in Java

  • 2. Opening the World of Potential Java programs are made of objects that interact with each other ◦ Each object is based on a class ◦ A class describes a set of objects with the same behavior Each class defines a specific set of methods to use with its objects ◦ For example, the String class provides methods: ◦ Examples: length() and charAt() methods String greeting = “Hello World”; int len = greeting.length(); char c1 = greeting.charAt(0);
  • 3. Diagram of a Class Private Data ◦ Each object has its own private data that other objects cannot directly access ◦ Methods of the public interface provide access to private data, while hiding implementation details: ◦ This is called Encapsulation Public Interface ◦ Each object has a set of methods available for other objects to use Class Private Data (Variables) Public Interface (Methods)
  • 4. Public Interface of a Class Why do you need a class? ◦ What tasks will this class perform? ◦ What methods will you need? ◦ What parameters will the methods need to receive? ◦ What will the methods return? Task Method Returns Add the price of an item addItem(double) void Get the total amount owed getTotal() double Get the count of items purchased getCount() int Clear the cash register for a new sale clear() void
  • 5. To create a Class You need: ◦ Public class name ◦ Private instance variables ◦ Constructors ◦ Getters & Setters ◦ Helper methods
  • 6. Classes – Instance Variables Each object instantiated from the class has its own set of instance variables ◦ Instance variables describe the class ◦ They store the state of the object Defining instance variables: ◦ Access Specifiers ◦ Classes (and interface methods) are public ◦ Instance variables are always private ◦ DataType ◦ Instance Variable name – EXTREMELY IMPORTANT TO USE CAMEL CASING
  • 7. public class Animal private String type; private String name; private double weight; private int age; Private access modifiers mean the variable is only accessible within the class.
  • 8. Accessing Instance Variables public static void main(String[] args) { . . . System.out.println( cat.age ); // Error . . . } The compiler will not allow this violation of privacy  Use accessor methods of the class instead! public static void main(String[] args) { . . . System.out.println( cat.getAge() ); // OK . . . } Encapsulation provides a public interface and hides the implementation details.
  • 9. Accessor and Mutator Methods 1) Accessor Methods: 'get' methods ◦ Asks the object for information without changing it ◦ Normally return a value of some type 2) Mutator Methods: 'set' methods ◦ Changes values in the object ◦ Usually take a parameter that will change an instance variable ◦ Normally return void public void addItem(double price) { } public void clear() { } public double getTotal() { } public int getCount() { }
  • 10. Constructors A constructor is a method that initializes instance variables of an object ◦ It is automatically called when an object is created ◦ It has exactly the same name as the class public class Animal { . . . public Animal() // A default no-arg constructor { } } Constructors never return values, but do not use void in their declaration
  • 11. POJO Characteristics All POJOs MUST HAVE A DEFAULT NO-ARG CONSTRUCTOR ◦ (yes, I‘m yelling about it!) Either implicit or explicit ◦ Implicit – assumes one but not specifically defined ◦ Explicit – if you have a non-default constructor, you must add in a default no-arg constructor
  • 12. The Default Constructor If you do not supply any constructors, the compiler will make a default constructor automatically ◦ It takes no parameters ◦ It initializes all instance variables public class Animal { . . . /** Does exactly what a compiler generated constructor would do. */ public Animal() { //all instance variables would be set to a default value } } By default, numbers are initialized to 0, booleans to false, and objects as null.
  • 13. Multiple Constructors A class can have more than one constructor ◦ Each must have a unique set of parameters public class Animal { . . . /** Constructs an animal with no features */ public Animal( ) { . . . } // default no-arg constructor /** Constructs an animal with a type @param type the type of animal */ public Animal(String type) { . . . } // a non-default constructor } The compiler picks the constructor that matches the construction parameters.
  • 14. Common Error – Declaring a Constructor as void ◦ Constructors have no return type ◦ This creates a method with a return type of void which is NOT a constructor! ◦ The Java compiler does not consider this an error public class Animal { /** Intended to be a constructor. */ public void Animal( ) { . . . } } Not a constructor…. Just another method that returns nothing (void)
  • 15. Constructors are defined in the class. public class Animal Constructors are used to create the objects in another class. public class AnimalTester public static void main(String[] args)
  • 16. Overloading Constructors ◦ Multiple constructors can have exactly the same name ◦ They require different lists of parameters ◦ Actually any method can be overloaded ◦ Same method name with different parameters public Animal() { . . . } public Animal(String type) { . . . } public Animal(String type, String name) { . . . } public Animal(String type, String name, int age) { . . . } public Animal(String name) { . . . }
  • 17. Helper Methods toString( ) to see what is inside the instance variables Other methods needed to use the class haveBirthday( ) to add another year to the age loseWeight(double weightLoss) to remove pounds gainWeight(double weightGain) to add more pounds
  • 18. Constructor this reference Use the this reference in constructors ◦ It makes it very clear that you are setting the instance variable: public class Animal { private String name; public Animal(String name) { this.name = name; } }
  • 19. public class AnimalTester { public static void main(String[] args) { Animal dog = new Animal(); ... Testing a Class We wrote an Animal class but… ◦ You cannot execute the class – it has no main method It can become part of a larger program ◦ Test it first though with unit testing To test a new class, you can use: ◦ Junit ◦ Or write a tester class: ◦ With a main
  • 20. Instantiating Objects Objects are created based on classes ◦ Use the new operator to construct objects ◦ Give each object a unique name (like variables) You have used the new operator before: These do NOT go into the class definition file! Scanner in = new Scanner(System.in);
  • 21. Separating the View and Model Scanners go in the main method No sysouts in the classes – except for testing. Comment them out before submission. ✔ MVC View Pattern – Model View Controller
  • 22. Use the new operator to construct objects of a class. Animal penguin = new Animal(); Animal cat = new Animal(); Object nameClass name Class name Creating two instances of Animals objects AnimalTester.java Add a main method
  • 23. public class AnimalTester { public static void main(String[] args) { Animal dog = new Animal(); dog.setType(“Dog”); sysout(dog.toString( )); Animal tiger = new Animal(“Tiger”); sysout(tiger.toString( ));
  • 24. Name Bark Leaves Leaf Size in cm Fruit Zone of Tree Hardiness Hackberry flaky 3 veins at base 9 TRUE 6 Red oak smooth matte, variable 20 FALSE 3 English Walnut smooth plates between fissures leaflets 45 TRUE 8
  • 25. Name Bark Leaves Leaf Size in cm Fruit Zone of Tree Hardiness Hackberry flaky 3 veins at base 9 TRUE 6 Red oak smooth matte, variable 20 FALSE 3 English Walnut smooth plates between fissures leaflets 45 TRUE 8