SlideShare una empresa de Scribd logo
1 de 14
Mutable and
immutable
  classes
AGENDA

• Introduction

• Mutable Classes

• Immutable Classes

• Cloning and Mutable

• Conclusion
Introduction

 An Immutable object is a kind of object whose
  state cannot be modified after it is created where
  a Mutable Object can be modified after it is
  created.
Immutable
 A class that contains methods (other than
  constructors) that change any of the data in an
  object of the class is called immutable classes
  and object of the class are called immutable
  objects.
 Strings are immutable class.
 In Java, objects are referred by references.
 If an object is known to be immutable, the
  object reference can be shared.
 For   example, Boolean, Byte, Character,
  Double, Float, Integer, Long, Short, and String
  are immutable classes in Java.
 An immutable object is one whose externally
  visible state cannot change after it is
  instantiated.
 The String, Integer, and BigDecimal classes in
 the Java class library are examples of
 immutable objects -- they represent a single
 value that cannot change over the lifetime of
 the object.
Sample Program
Class Pro1
{
    public static void main(String[] args)
     {
          String str = "WELCOME";
          System.out.println(str);
          str.toLowerCase(); //Doesn’t impact on original content of Str
          System.out.println(str);                   Output
     }                                              WELCOME
}                                                   WELCOME
Modified Program

class Pro1
{
    public static void main(String[] args)
    {
        String str = “WELCOME";
        System.out.println(str);
        String str1 = str.toLower();
        System.out.println(str1);            Output
    }                                        WELCOME
}                                            welcome
Mutable
 A class that contains public methods or input
  methods that can change the data in an object
  of the class is called mutable classes and the object
  of the class are called mutable objects.
 The class Date is an example of a mutable class.
 When defining any methods , that method should
  not return a reference to a mutable object.
 Instead use a copy constructor to return a
  reference to a completely independent copy of
  the mutable object.
 A String Buffer is a string that can be changed. String
  Buffers are Mutable , they’re not inherently thread safe
  and thus many of the methods of String Buffer class
  are synchronized.


 The StringBuffer has the methods
      Append( )
      Insert ( )
Mutable Objects in AWT and Swing
 The java.awt package defines several classes that encapsulate
  geometric information.
                  AWT Geometry Classes
      CLASS                   DESCRIPTION
      Point                   (x , y) location in space

      Dimension               Component width and
                              height
      Insets                  Representation of the
                              Borders of a container
      Rectangle               Area in a coordinate
                              space
 The java.awt.Component and java.awt.Container
  classes define methods to access certain geometric
  information.
      public Point getLocation();
      public void setLocation( Point loc);
      public Dimension getSize();
      public void setSize(Dimension size);
      public Insets getInsets();
      public void setInsets(Insets insets);
      public Rectangle getBounds();
      public void setBounds(Rectangle bounds);
Cloning and mutable objects

 All classes that implement Cloneable should override
  clone with a public method whose return type is the
  class itself.
 This method should call super.clone and then fix any
  fields that need to be fixed.
 Typically this means copying any mutable objects
  that comprise the internal deep structure of object
  being cloned and replacing the clone’s references to
  these objects with references to the copies.
Reference

1. Absolute JAVA – Walter Savitch
2. Effective Java – Joshua Bloch


Websites

www.sun.com
www.google.com
Mutable and  immutable classes

Más contenido relacionado

La actualidad más candente

Collections In Java
Collections In JavaCollections In Java
Collections In Java
Binoj T E
 
class and objects
class and objectsclass and objects
class and objects
Payel Guria
 

La actualidad más candente (20)

Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Inheritance in OOPS
Inheritance in OOPSInheritance in OOPS
Inheritance in OOPS
 
XML Schema
XML SchemaXML Schema
XML Schema
 
Java swing
Java swingJava swing
Java swing
 
Wrapper classes
Wrapper classes Wrapper classes
Wrapper classes
 
Files in java
Files in javaFiles in java
Files in java
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
class and objects
class and objectsclass and objects
class and objects
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Constants in java
Constants in javaConstants in java
Constants in java
 
input/ output in java
input/ output  in javainput/ output  in java
input/ output in java
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdfCS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
 
Command line arguments
Command line argumentsCommand line arguments
Command line arguments
 

Destacado

Trends and technologies in system softwares
Trends and technologies in system softwaresTrends and technologies in system softwares
Trends and technologies in system softwares
Tech_MX
 
09 binary-trees
09 binary-trees09 binary-trees
09 binary-trees
Tech_MX
 
14.jun.2012
14.jun.201214.jun.2012
14.jun.2012
Tech_MX
 
Constants
ConstantsConstants
Constants
Tech_MX
 
Graph theory
Graph theoryGraph theory
Graph theory
Tech_MX
 
More on Lex
More on LexMore on Lex
More on Lex
Tech_MX
 
What are interpersonal skills
What are interpersonal skillsWhat are interpersonal skills
What are interpersonal skills
Tech_MX
 
Linear programming problem
Linear programming problemLinear programming problem
Linear programming problem
Tech_MX
 
Investment problem
Investment problemInvestment problem
Investment problem
Tech_MX
 
Set data structure 2
Set data structure 2Set data structure 2
Set data structure 2
Tech_MX
 
Buddy system final
Buddy system finalBuddy system final
Buddy system final
Tech_MX
 
Set data structure
Set data structure Set data structure
Set data structure
Tech_MX
 
Graph data structure
Graph data structureGraph data structure
Graph data structure
Tech_MX
 
Inline function
Inline functionInline function
Inline function
Tech_MX
 
E post office system
E post office systemE post office system
E post office system
Tech_MX
 
Combined paging and segmentation
Combined paging and segmentationCombined paging and segmentation
Combined paging and segmentation
Tech_MX
 

Destacado (20)

Trends and technologies in system softwares
Trends and technologies in system softwaresTrends and technologies in system softwares
Trends and technologies in system softwares
 
09 binary-trees
09 binary-trees09 binary-trees
09 binary-trees
 
14.jun.2012
14.jun.201214.jun.2012
14.jun.2012
 
Constants
ConstantsConstants
Constants
 
Graph theory
Graph theoryGraph theory
Graph theory
 
More on Lex
More on LexMore on Lex
More on Lex
 
What are interpersonal skills
What are interpersonal skillsWhat are interpersonal skills
What are interpersonal skills
 
Linear programming problem
Linear programming problemLinear programming problem
Linear programming problem
 
Investment problem
Investment problemInvestment problem
Investment problem
 
Set data structure 2
Set data structure 2Set data structure 2
Set data structure 2
 
Buddy system final
Buddy system finalBuddy system final
Buddy system final
 
Set data structure
Set data structure Set data structure
Set data structure
 
Storage Class Specifiers in C++
Storage Class Specifiers in C++Storage Class Specifiers in C++
Storage Class Specifiers in C++
 
Graph data structure
Graph data structureGraph data structure
Graph data structure
 
Inline function
Inline functionInline function
Inline function
 
E post office system
E post office systemE post office system
E post office system
 
Combined paging and segmentation
Combined paging and segmentationCombined paging and segmentation
Combined paging and segmentation
 
Linkers
LinkersLinkers
Linkers
 
Uid
UidUid
Uid
 
Spss
SpssSpss
Spss
 

Similar a Mutable and immutable classes

Similar a Mutable and immutable classes (20)

Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
 
Basic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentBasic concept of class, method , command line-argument
Basic concept of class, method , command line-argument
 
Java defining classes
Java defining classes Java defining classes
Java defining classes
 
Java basics
Java basicsJava basics
Java basics
 
Lecture 8 Library classes
Lecture 8 Library classesLecture 8 Library classes
Lecture 8 Library classes
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
 
Java As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & AppletsJava As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & Applets
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3
 
PPT Lecture-1.4.pptx
PPT Lecture-1.4.pptxPPT Lecture-1.4.pptx
PPT Lecture-1.4.pptx
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptx
 
Java mcq
Java mcqJava mcq
Java mcq
 
classandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.pptclassandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.ppt
 
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
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3
 
Using class and object java
Using class and object javaUsing class and object java
Using class and object java
 

Más de Tech_MX

Virtual base class
Virtual base classVirtual base class
Virtual base class
Tech_MX
 
Theory of estimation
Theory of estimationTheory of estimation
Theory of estimation
Tech_MX
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
Tech_MX
 
String & its application
String & its applicationString & its application
String & its application
Tech_MX
 
Statistical quality__control_2
Statistical  quality__control_2Statistical  quality__control_2
Statistical quality__control_2
Tech_MX
 
Stack data structure
Stack data structureStack data structure
Stack data structure
Tech_MX
 
Stack Data Structure & It's Application
Stack Data Structure & It's Application Stack Data Structure & It's Application
Stack Data Structure & It's Application
Tech_MX
 
Spanning trees & applications
Spanning trees & applicationsSpanning trees & applications
Spanning trees & applications
Tech_MX
 
Real time Operating System
Real time Operating SystemReal time Operating System
Real time Operating System
Tech_MX
 
Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)
Tech_MX
 
Motherboard of a pc
Motherboard of a pcMotherboard of a pc
Motherboard of a pc
Tech_MX
 
MultiMedia dbms
MultiMedia dbmsMultiMedia dbms
MultiMedia dbms
Tech_MX
 
Merging files (Data Structure)
Merging files (Data Structure)Merging files (Data Structure)
Merging files (Data Structure)
Tech_MX
 
Memory dbms
Memory dbmsMemory dbms
Memory dbms
Tech_MX
 
Linear regression
Linear regressionLinear regression
Linear regression
Tech_MX
 
Keyboard interrupt
Keyboard interruptKeyboard interrupt
Keyboard interrupt
Tech_MX
 
Introduction to loaders
Introduction to loadersIntroduction to loaders
Introduction to loaders
Tech_MX
 
Interpersonal communication
Interpersonal communicationInterpersonal communication
Interpersonal communication
Tech_MX
 
Interesting applications of graph theory
Interesting applications of graph theoryInteresting applications of graph theory
Interesting applications of graph theory
Tech_MX
 

Más de Tech_MX (20)

Virtual base class
Virtual base classVirtual base class
Virtual base class
 
Theory of estimation
Theory of estimationTheory of estimation
Theory of estimation
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
String & its application
String & its applicationString & its application
String & its application
 
Statistical quality__control_2
Statistical  quality__control_2Statistical  quality__control_2
Statistical quality__control_2
 
Stack data structure
Stack data structureStack data structure
Stack data structure
 
Stack Data Structure & It's Application
Stack Data Structure & It's Application Stack Data Structure & It's Application
Stack Data Structure & It's Application
 
Spanning trees & applications
Spanning trees & applicationsSpanning trees & applications
Spanning trees & applications
 
Real time Operating System
Real time Operating SystemReal time Operating System
Real time Operating System
 
Parsing
ParsingParsing
Parsing
 
Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)
 
Motherboard of a pc
Motherboard of a pcMotherboard of a pc
Motherboard of a pc
 
MultiMedia dbms
MultiMedia dbmsMultiMedia dbms
MultiMedia dbms
 
Merging files (Data Structure)
Merging files (Data Structure)Merging files (Data Structure)
Merging files (Data Structure)
 
Memory dbms
Memory dbmsMemory dbms
Memory dbms
 
Linear regression
Linear regressionLinear regression
Linear regression
 
Keyboard interrupt
Keyboard interruptKeyboard interrupt
Keyboard interrupt
 
Introduction to loaders
Introduction to loadersIntroduction to loaders
Introduction to loaders
 
Interpersonal communication
Interpersonal communicationInterpersonal communication
Interpersonal communication
 
Interesting applications of graph theory
Interesting applications of graph theoryInteresting applications of graph theory
Interesting applications of graph theory
 

Último

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Último (20)

Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 

Mutable and immutable classes

  • 2. AGENDA • Introduction • Mutable Classes • Immutable Classes • Cloning and Mutable • Conclusion
  • 3. Introduction  An Immutable object is a kind of object whose state cannot be modified after it is created where a Mutable Object can be modified after it is created.
  • 4. Immutable  A class that contains methods (other than constructors) that change any of the data in an object of the class is called immutable classes and object of the class are called immutable objects.  Strings are immutable class.  In Java, objects are referred by references.  If an object is known to be immutable, the object reference can be shared.
  • 5.  For example, Boolean, Byte, Character, Double, Float, Integer, Long, Short, and String are immutable classes in Java.  An immutable object is one whose externally visible state cannot change after it is instantiated.  The String, Integer, and BigDecimal classes in the Java class library are examples of immutable objects -- they represent a single value that cannot change over the lifetime of the object.
  • 6. Sample Program Class Pro1 { public static void main(String[] args) { String str = "WELCOME"; System.out.println(str); str.toLowerCase(); //Doesn’t impact on original content of Str System.out.println(str); Output } WELCOME } WELCOME
  • 7. Modified Program class Pro1 { public static void main(String[] args) { String str = “WELCOME"; System.out.println(str); String str1 = str.toLower(); System.out.println(str1); Output } WELCOME } welcome
  • 8. Mutable  A class that contains public methods or input methods that can change the data in an object of the class is called mutable classes and the object of the class are called mutable objects.  The class Date is an example of a mutable class.  When defining any methods , that method should not return a reference to a mutable object.  Instead use a copy constructor to return a reference to a completely independent copy of the mutable object.
  • 9.  A String Buffer is a string that can be changed. String Buffers are Mutable , they’re not inherently thread safe and thus many of the methods of String Buffer class are synchronized.  The StringBuffer has the methods Append( ) Insert ( )
  • 10. Mutable Objects in AWT and Swing  The java.awt package defines several classes that encapsulate geometric information. AWT Geometry Classes CLASS DESCRIPTION Point (x , y) location in space Dimension Component width and height Insets Representation of the Borders of a container Rectangle Area in a coordinate space
  • 11.  The java.awt.Component and java.awt.Container classes define methods to access certain geometric information. public Point getLocation(); public void setLocation( Point loc); public Dimension getSize(); public void setSize(Dimension size); public Insets getInsets(); public void setInsets(Insets insets); public Rectangle getBounds(); public void setBounds(Rectangle bounds);
  • 12. Cloning and mutable objects  All classes that implement Cloneable should override clone with a public method whose return type is the class itself.  This method should call super.clone and then fix any fields that need to be fixed.  Typically this means copying any mutable objects that comprise the internal deep structure of object being cloned and replacing the clone’s references to these objects with references to the copies.
  • 13. Reference 1. Absolute JAVA – Walter Savitch 2. Effective Java – Joshua Bloch Websites www.sun.com www.google.com