SlideShare una empresa de Scribd logo
1 de 53
Classes and Objects Defining Classes and Objects
Contents ,[object Object],[object Object],[object Object],[object Object],[object Object]
Defining  S imple  C lasses
What a Class Should Contain? ,[object Object],[object Object],[object Object],[object Object]
Defining Classes ,[object Object],public class Cat extends Animal { private String name; public Cat(String name) { this.name = name; } public void SayMiau() { System.out.printf("Cat %s said: Miauuuuuu!", name); } } Class Field Constructor Method
Elements of Class Definitions ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Defining  S imple  C lasses Examples
Task: Define a Class ,[object Object],[object Object],[object Object],[object Object],[object Object]
Defining Simple Class ,[object Object],public class Cat { private String name; public String getName() { return this.name; } public void setName(String name) { this.name = name; } // (The example continues on the next slide) Class definition Field definition Property getter Property setter
Defining Simple Class (2) public Cat() { this.name = "Nastradin"; } public Cat(String name) { this.name = name; } public void  s ayMiau() { System.out.printf( "Cat %s said: Miauuuuuu!%n", name); } }  Method definition Constructor definition Constructor definition
Using  C lasses
What to Do With Classes? ,[object Object],[object Object],[object Object],[object Object],[object Object]
How to Use Classes? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Using  C lasses Example
Task: Cat Meeting ,[object Object],[object Object],[object Object],[object Object],[object Object]
Manipulating Class Instances ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],// (The example continues on the next slide)
Manipulating Class Instances (2) Cat[] cats = new Cat[] {   firstCat,    secondCat,    thirdCat }; for(Cat cat  :  cats)   {  cat.SayMiau();  } }
Using  C lasses  in Java Live Demo
Constructors Defining and Using Constructors in the Classes
What is a Constructor? ,[object Object],[object Object],[object Object]
Defining Constructors ,[object Object],[object Object],[object Object],[object Object],public class Point   { private int xCoord; private int yCoord; public Point()  {  //  S imple default constructor xCoord = 0; yCoord = 0; } // More code ... }
Constructors Examples
Defining Constructors public class Person { private String name; private int age; // Default constructor public Person() { this.name = null; this.age = 0; } // Constructor with parameters public Person(String name, int age) { this.name = name; this.age = age; } //More code ...  }
Indirect Constructors ,[object Object],p ublic class ClockAlarm { private int hours = 0; // Inline field initializatio n private int minutes = 0; // Inline field initialization // Default constructor public ClockAlarm() { } // Constructor with parameters p ublic ClockAlarm(int hours, int minutes) { this.hours = hours; this.minutes = minutes; } // More code ... }
Advanced Techniques ,[object Object],public class Point { // Definition of fields (member variables) private int xCoord; private int yCoord; private String name; // The default constructor calls the other constructor public Point() { this(0, 0); } // Constructor to parameters public Point(int xCoord, int yCoord) { this.xCoord = xCoord; this.yCoord = yCoord; name = String.format("(%d,%d)", this.xCoord,      this.yCoord); } // More code ... }
Constructors Live Demo
Properties Defining and Using Properties
What is a Property ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Defining Properties ,[object Object],[object Object],[object Object],[object Object],[object Object],public class Point   { private int xCoord; public int getXCoord() { return xCoord; } public void setXCoord(int coord) { xCoord = coord; } }
Properties Examples
Capsulate Fields public class Point  { private  int xCoord; private  int yCoord; // constructing code ... public int getXCoord() { return this.xCoord; } public void setXCoord(int value) { this.xCoord = value; } public int get Y Coord() { return this. y Coord; } public void set Y Coord(int value) { this. y Coord = value; } // More code ... }  Fields are encapsulated as private members Getters and Setter allow controlled access to the private fields
Dynamic Properties ,[object Object],public class Rectangle { private float width; private float height; public Rectangle(float width, float height) { // Some initialization code } public float getArea() { return width * height; } }
Properties Live Demo
Static Members Static vs. Instance Fields, Methods and Properties
What is  static ? ,[object Object],[object Object],[object Object],[object Object],[object Object]
Static vs. Non-Static ,[object Object],[object Object],[object Object],[object Object]
Static Members Examples
Static Members – Example public class Sequence { private static int currentValue = 0; private Sequence() { // Deny instantiation of this class } public static int nextValue() { currentValue++; return currentValue; } } public class TestSequence { public static void main(String[] args) { System.out.printf("Sequence[1..3]: %d, %d, %d ",  Sequence.nextValue(), Sequence.nextValue(),  Sequence.nextValue()); } }
Static Members Live Demo
Creating Static Methods public class Fraction   { private int numerator; private int denominator; public Fraction(int num, int denom)   { this.numerator = num; this.denominator = denom; } public  static  Fraction Parse( S tring val)   { S tring[] parts = val. s plit( " / " ); int num = Integer.parseInt(parts[0]); int denom = Integer.parseInt(parts[1]); Fraction result = new Fraction(num, denom); return result; } }
Calling Static Methods ,[object Object],public static void main(String[] args) { String fractStr = "2/3"; try { fraction =  Fraction.Parse (fractStr); System.out.println("fraction = " + fraction); } catch (Exception ex) { System.out.println("Can not parse the fraction."); } }
Parsing Fractions Live Demo
Summary ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Lecture Topic ,[object Object]
Exercises ,[object Object],[object Object],[object Object]
Exercises (2) ,[object Object],[object Object],[object Object],[object Object]
Exercises (3) ,[object Object],[object Object]
Exercises (4) ,[object Object],[object Object],[object Object]
Exercises (5) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Exercises (6) ,[object Object],[object Object],[object Object],[object Object]
Exercises (7) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Exercises (8) ,[object Object],[object Object],[object Object],[object Object]
Exercises (9) ,[object Object],[object Object],[object Object]

Más contenido relacionado

La actualidad más candente

How to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programmingHow to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programming
Syed Faizan Hassan
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
Abhilash Nair
 

La actualidad más candente (19)

11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objects
 
Object and class
Object and classObject and class
Object and class
 
Class & Object - Intro
Class & Object - IntroClass & Object - Intro
Class & Object - Intro
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
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
 
Week9 Intro to classes and objects in Java
Week9 Intro to classes and objects in JavaWeek9 Intro to classes and objects in Java
Week9 Intro to classes and objects in Java
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Class or Object
Class or ObjectClass or Object
Class or Object
 
Csharp_Chap03
Csharp_Chap03Csharp_Chap03
Csharp_Chap03
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
C++ And Object in lecture3
C++  And Object in lecture3C++  And Object in lecture3
C++ And Object in lecture3
 
Lecture 7 arrays
Lecture   7 arraysLecture   7 arrays
Lecture 7 arrays
 
03class
03class03class
03class
 
Class and object in C++ By Pawan Thakur
Class and object in C++ By Pawan ThakurClass and object in C++ By Pawan Thakur
Class and object in C++ By Pawan Thakur
 
Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in java
 
How to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programmingHow to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programming
 
CLASS & OBJECT IN JAVA
CLASS & OBJECT  IN JAVACLASS & OBJECT  IN JAVA
CLASS & OBJECT IN JAVA
 
Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in Python
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 

Destacado

حملة عمر بلدك
حملة عمر بلدكحملة عمر بلدك
حملة عمر بلدك
Alaa Wahba
 

Destacado (18)

Digitalisaatio ja valtioneuvosto
Digitalisaatio ja valtioneuvostoDigitalisaatio ja valtioneuvosto
Digitalisaatio ja valtioneuvosto
 
Talk nerdy to me!
Talk nerdy to me!Talk nerdy to me!
Talk nerdy to me!
 
LESTER_ANTONY_FRANCIS ( Aug 2016)
LESTER_ANTONY_FRANCIS ( Aug 2016)LESTER_ANTONY_FRANCIS ( Aug 2016)
LESTER_ANTONY_FRANCIS ( Aug 2016)
 
Adobe Flash, entre el amor y el odio
Adobe Flash, entre el amor y el odioAdobe Flash, entre el amor y el odio
Adobe Flash, entre el amor y el odio
 
Methods intro-1.0
Methods intro-1.0Methods intro-1.0
Methods intro-1.0
 
About the-course
About the-courseAbout the-course
About the-course
 
書籍市場の現状
書籍市場の現状書籍市場の現状
書籍市場の現状
 
Leveraging Social Media Tools
Leveraging Social Media ToolsLeveraging Social Media Tools
Leveraging Social Media Tools
 
World Economic Forum on Africa 2006
World Economic Forum on Africa 2006World Economic Forum on Africa 2006
World Economic Forum on Africa 2006
 
Espirometría
EspirometríaEspirometría
Espirometría
 
Καινοτομια
ΚαινοτομιαΚαινοτομια
Καινοτομια
 
On the frontier of genotype-2-phenotype data integration
On the frontier of genotype-2-phenotype data integrationOn the frontier of genotype-2-phenotype data integration
On the frontier of genotype-2-phenotype data integration
 
Estudiante virtual exioso
Estudiante virtual exiosoEstudiante virtual exioso
Estudiante virtual exioso
 
ChefConf2014 - Chef TDD
ChefConf2014 - Chef TDD ChefConf2014 - Chef TDD
ChefConf2014 - Chef TDD
 
Code iscool
Code iscoolCode iscool
Code iscool
 
Teatro s. XVII
Teatro s. XVIITeatro s. XVII
Teatro s. XVII
 
حملة عمر بلدك
حملة عمر بلدكحملة عمر بلدك
حملة عمر بلدك
 
Basic computer
Basic computerBasic computer
Basic computer
 

Similar a Defining classes-and-objects-1.0

Object-Oriented Programming with C#
Object-Oriented Programming with C#Object-Oriented Programming with C#
Object-Oriented Programming with C#
Svetlin Nakov
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08
Terry Yoast
 
Defining classes-part-i-constructors-properties
Defining classes-part-i-constructors-propertiesDefining classes-part-i-constructors-properties
Defining classes-part-i-constructors-properties
CtOlaf
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6
sotlsoc
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
Abed Bukhari
 

Similar a Defining classes-and-objects-1.0 (20)

14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining Classes
 
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
 
Object-Oriented Programming with C#
Object-Oriented Programming with C#Object-Oriented Programming with C#
Object-Oriented Programming with C#
 
Chap08
Chap08Chap08
Chap08
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
Java Reflection
Java ReflectionJava Reflection
Java Reflection
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
OOP Lab Report.docx
OOP Lab Report.docxOOP Lab Report.docx
OOP Lab Report.docx
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
 
Core java concepts
Core java concepts Core java concepts
Core java concepts
 
Core Java
Core JavaCore Java
Core Java
 
Defining classes-part-i-constructors-properties
Defining classes-part-i-constructors-propertiesDefining classes-part-i-constructors-properties
Defining classes-part-i-constructors-properties
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6
 
object oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoMobject oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoM
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
 
Java Concepts
Java ConceptsJava Concepts
Java Concepts
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
 

Más de BG Java EE Course

Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advanced
BG Java EE Course
 
JavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsJavaScript and jQuery Fundamentals
JavaScript and jQuery Fundamentals
BG Java EE Course
 
Creating Web Sites with HTML and CSS
Creating Web Sites with HTML and CSSCreating Web Sites with HTML and CSS
Creating Web Sites with HTML and CSS
BG Java EE Course
 

Más de BG Java EE Course (20)

Rich faces
Rich facesRich faces
Rich faces
 
JSP Custom Tags
JSP Custom TagsJSP Custom Tags
JSP Custom Tags
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advanced
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - Basics
 
JSTL
JSTLJSTL
JSTL
 
Unified Expression Language
Unified Expression LanguageUnified Expression Language
Unified Expression Language
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Web Applications and Deployment
Web Applications and DeploymentWeb Applications and Deployment
Web Applications and Deployment
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
CSS
CSSCSS
CSS
 
HTML: Tables and Forms
HTML: Tables and FormsHTML: Tables and Forms
HTML: Tables and Forms
 
HTML Fundamentals
HTML FundamentalsHTML Fundamentals
HTML Fundamentals
 
WWW and HTTP
WWW and HTTPWWW and HTTP
WWW and HTTP
 
JavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsJavaScript and jQuery Fundamentals
JavaScript and jQuery Fundamentals
 
Creating Web Sites with HTML and CSS
Creating Web Sites with HTML and CSSCreating Web Sites with HTML and CSS
Creating Web Sites with HTML and CSS
 
Processing XML with Java
Processing XML with JavaProcessing XML with Java
Processing XML with Java
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
 
Introduction to-RDBMS-systems
Introduction to-RDBMS-systemsIntroduction to-RDBMS-systems
Introduction to-RDBMS-systems
 

Último

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
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Último (20)

FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
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
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
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...
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
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
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
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...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 

Defining classes-and-objects-1.0

  • 1. Classes and Objects Defining Classes and Objects
  • 2.
  • 3. Defining S imple C lasses
  • 4.
  • 5.
  • 6.
  • 7. Defining S imple C lasses Examples
  • 8.
  • 9.
  • 10. Defining Simple Class (2) public Cat() { this.name = "Nastradin"; } public Cat(String name) { this.name = name; } public void s ayMiau() { System.out.printf( "Cat %s said: Miauuuuuu!%n", name); } } Method definition Constructor definition Constructor definition
  • 11. Using C lasses
  • 12.
  • 13.
  • 14. Using C lasses Example
  • 15.
  • 16.
  • 17. Manipulating Class Instances (2) Cat[] cats = new Cat[] { firstCat, secondCat, thirdCat }; for(Cat cat : cats) { cat.SayMiau(); } }
  • 18. Using C lasses in Java Live Demo
  • 19. Constructors Defining and Using Constructors in the Classes
  • 20.
  • 21.
  • 23. Defining Constructors public class Person { private String name; private int age; // Default constructor public Person() { this.name = null; this.age = 0; } // Constructor with parameters public Person(String name, int age) { this.name = name; this.age = age; } //More code ... }
  • 24.
  • 25.
  • 27. Properties Defining and Using Properties
  • 28.
  • 29.
  • 31. Capsulate Fields public class Point { private int xCoord; private int yCoord; // constructing code ... public int getXCoord() { return this.xCoord; } public void setXCoord(int value) { this.xCoord = value; } public int get Y Coord() { return this. y Coord; } public void set Y Coord(int value) { this. y Coord = value; } // More code ... } Fields are encapsulated as private members Getters and Setter allow controlled access to the private fields
  • 32.
  • 34. Static Members Static vs. Instance Fields, Methods and Properties
  • 35.
  • 36.
  • 38. Static Members – Example public class Sequence { private static int currentValue = 0; private Sequence() { // Deny instantiation of this class } public static int nextValue() { currentValue++; return currentValue; } } public class TestSequence { public static void main(String[] args) { System.out.printf("Sequence[1..3]: %d, %d, %d ", Sequence.nextValue(), Sequence.nextValue(), Sequence.nextValue()); } }
  • 40. Creating Static Methods public class Fraction { private int numerator; private int denominator; public Fraction(int num, int denom) { this.numerator = num; this.denominator = denom; } public static Fraction Parse( S tring val) { S tring[] parts = val. s plit( " / " ); int num = Integer.parseInt(parts[0]); int denom = Integer.parseInt(parts[1]); Fraction result = new Fraction(num, denom); return result; } }
  • 41.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.