SlideShare a Scribd company logo
1 of 49
Download to read offline
Defining Classes in JAVA
Mehdi Ali Soltani
mehdi.alisoltani@gmail.com
https://www.linkedin.com/in/mehdi-ali-soltani-315453b7/
WHAT IS A CLASS?
A class is a prescription for a particular kind of object.
Class Properties
➢ Fields: These are variables that store data items that typically differentiate
one object of the class from another. They are also referred to as data
members of a class.
➢ Methods: These define the operations you can perform for the class so they
determine what you can do to, or with, objects of the class. Methods typically
operate on the fields the data members of the class.
Static and non Static Fields
➢ Non-static fields, also called instance variables :
Each object of the class has its own copy of each of the non-static fields or
instance variables that appear in the class definition.
➢ Static fields, also called class variables
A given class has only one copy of each of its static fields or class variables,
and these are shared between and among all the objects of the class
Static and non Static Fields Example
➢ instance methods
instance methods can be executed only in relation to a particular object
MyObject obj = new MyObject();//Create an instance
obj.nonstaticMethod();//Refer to the instance's class's code
➢ class methods
Class method can be executed even when no objects of a class exist
e.g main(), Math.sqrt(), ...
Methods in a Class Definition
Accessing Variables and Methods
➢ static method
double rootPi = Math.sqrt(Math.PI);
➢ Non static method
double ballVolume = ball.volume();
Final Fields
final fields means that the field cannot be modified by the methods in the class
final double PI = 3.14;
You should provide an initial value for a final field when you declare it.
definition of the Sphere class
DEFINING CLASSES
Basic Structure of a Method
Returning from a Method
To return a value from a method when its execution is complete use a return
statement.
return return_value;
The Parameter List
Parameter and an argument:
➢ A parameter has a name and a type and appears in the parameter list in the
definition of a method. A parameter defines the type of value that can be
passed to the method when it is called.
➢ An argument is a value that is passed to a method when it is executed, and
the value of the argument is referenced by the parameter name during
execution of the method
Definition of a Method
How Argument Values are Passed to a Method
All argument values are transferred to a method using what is called the
pass-by-value mechanism
A method can change an object that is passed as an argument. This is because a
variable of a class type contains a reference to an object, not the object itself.
Thus, when you use a variable of a class type as an argument to a method, a copy
of a reference to the object is passed to the method, not a copy of the object
itself. Because a copy of a reference still refers to the same object, the
parameter name used in the body of a method refers to the original object that
was passed as the argument.
Passing Objects to Methods
Final Parameters
Specifying any of the parameters for a method as final. This has the effect of
preventing modification of any argument value that is substituted for the
parameter when you call the method.
Defining Class Methods
Define a class method by adding the keyword static to its definition
Defining Class Methods(cont.)
Remember that you cannot directly refer to any of the instance variables in the
class within a static method. This is because a static method can be executed
when no objects of the class have been created, and therefore no instance
variables exist.
Defining Methods
Instance Method
Variable this
Every instance method has a variable with the name this that refers to the current
object for which the method is being called. The compiler uses this implicitly
when your method refers to an instance variable of the class
return 4.0/3.0*PI* this.radius *this.radius*this.radius;
Sources of Data Available within a Method
➢ Arguments passed to the method, which you refer to by using the parameter
names
➢ Data members, both instance variables and class variables, which you refer
to by their names
➢ Local variables that you declare in the body of the method
➢ Values that are returned by other methods that are called from within the
method
Initializing Data Members
CONSTRUCTORS
When you create an object of a class, a special kind of method called a
constructor is always invoked
If you don't define any constructors for your class, the compiler supplies a
default constructor in the class, which does nothing
Constructor Characteristics
➢ A constructor never returns a value, and you must not specify a return type
not even of type void
➢ A constructor always has the same name as the class.
Constructor Example
Creating Objects of a Class
Passing Objects to a Method
When you pass an object as an argument to a method, the mechanism that
applies is called pass-by-reference, because a copy of the reference contained in
the variable is transferred to the method, not a copy of the object itself.
Passing Objects to a Method
The Lifetime of an Object
The lifetime of an object is determined by the variable that holds the reference
you can reset a variable to refer to nothing by setting its value to null.
ball = null;
the variable ball no longer refers to an object. The lifetime of an object is
determined by whether any variable anywhere in the program still references it.
The process of disposing of dead objects is called garbage collection
USING A CLASS
METHOD OVERLOADING
Java enables you to define several methods in a class with the same name, as
long as each method has a unique set of parameters. Defining two or more
methods with the same name in a class is called method overloading
Different ways to overload the method
1. By changing number of arguments
2. By changing the data type
METHOD OVERLOADING
Multiple Constructors
Multiple Constructors
Creating object with different constructors
Calling a Constructor from a Constructor
One class constructor can call another constructor in the same class in its first
executable statement.
To refer to another constructor in the same class, use this as the method name,
followed by the appropriate arguments between parentheses
Calling a Constructor from a Constructor
Duplicating Objects Using a Constructor
Sphere eightBall = new Sphere(10.0, 10.0, 0.0);
Later in your program you want to create a new object newBall, which is identical
to the object eightBall.
If you write
Sphere newBall = eightBall;
variable newBall references the same object as eightBall. You don't have a
distinct object
Duplicating Objects Using a Constructor
duplicating an existing object by adding a constructor
UNDERSTANDING PACKAGES
package is a namespace that organizes a set of related classes and interfaces.
Conceptually you can think of packages as being similar to different folders on
your computer.
Some Important Packages in the Java Library
Adding Classes from a Package to Your Program
Import by using the import keyword:
import package.myclass;
CONTROLLING ACCESS TO CLASS MEMBERS
Provide you you control the accessibility of class members from outside the class.
Using Access Attributes
ATTRIBUTE PERMITTED ACCESS
No access attribute From methods in any class in the same package.
public From methods in any class anywhere as long as the
class has been declared as public.
private Accessible only from methods inside the class. No
access from outside the class at all.
protected From methods in any class in the same package
and from any subclass anywhere.
Allowed Between Classes within the same package
Access Between Different Packages
Specifying Access Attributes
…
…
Choosing Access Attributes
variables in a public class should be private and the methods that are called from
outside the class should be public.
➢ For classes in a package that are not public, and therefore not accessible outside the package, it
may sometimes be convenient to allow other classes in the package direct access to the data
members.
➢ If you have data members that have been specified as final so that their values are fi xed and they
are likely to be useful outside the class, you might as well declare them to be public.
➢ You may well have methods in a class that are intended to be used only internally by other
methods in the same class. In this case you should specify these as private.
➢ In a class like the standard class Math, which is just a convenient container for utility functions
and standard data values, you should make everything public.
NESTED CLASSES
All the classes you have defined so far have been separate from each other —
each stored away in its own source file. You can put the definition of one class
inside the definition of another class. The inside class is called a nested class. A
nested class can itself have another class nested inside it, if need be.
NESTED CLASSES (example)
Reference
Ivor Horton's Beginning Java®, Java 7 Edition
Published by
John Wiley & Sons, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2011 by John Wiley & Sons, Inc., Indianapolis, Indiana

More Related Content

What's hot

Top 100 Java Interview Questions with Detailed Answers
Top 100 Java Interview Questions with Detailed AnswersTop 100 Java Interview Questions with Detailed Answers
Top 100 Java Interview Questions with Detailed AnswersWhizlabs
 
JAVA Object Oriented Programming (OOP)
JAVA Object Oriented Programming (OOP)JAVA Object Oriented Programming (OOP)
JAVA Object Oriented Programming (OOP)Prof. Erwin Globio
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language Hitesh-Java
 
Object oriented programming-with_java
Object oriented programming-with_javaObject oriented programming-with_java
Object oriented programming-with_javaHoang Nguyen
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introductionSagar Verma
 
159747608 a-training-report-on
159747608 a-training-report-on159747608 a-training-report-on
159747608 a-training-report-onhomeworkping7
 
Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Kernel Training
 
Dev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdetDev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdetdevlabsalliance
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java ProgrammingMath-Circle
 
Core java lessons
Core java lessonsCore java lessons
Core java lessonsvivek shah
 
Top 10 Java Interview Questions and Answers 2014
Top 10 Java Interview Questions and Answers 2014 Top 10 Java Interview Questions and Answers 2014
Top 10 Java Interview Questions and Answers 2014 iimjobs and hirist
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2Sherihan Anver
 
Review Session and Attending Java Interviews
Review Session and Attending Java Interviews Review Session and Attending Java Interviews
Review Session and Attending Java Interviews Hitesh-Java
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1Sherihan Anver
 
Introduction to java 101
Introduction to java 101Introduction to java 101
Introduction to java 101kankemwa Ishaku
 

What's hot (19)

Top 100 Java Interview Questions with Detailed Answers
Top 100 Java Interview Questions with Detailed AnswersTop 100 Java Interview Questions with Detailed Answers
Top 100 Java Interview Questions with Detailed Answers
 
JAVA Object Oriented Programming (OOP)
JAVA Object Oriented Programming (OOP)JAVA Object Oriented Programming (OOP)
JAVA Object Oriented Programming (OOP)
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language
 
Object oriented programming-with_java
Object oriented programming-with_javaObject oriented programming-with_java
Object oriented programming-with_java
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introduction
 
159747608 a-training-report-on
159747608 a-training-report-on159747608 a-training-report-on
159747608 a-training-report-on
 
Java training in delhi
Java training in delhiJava training in delhi
Java training in delhi
 
Core Java
Core JavaCore Java
Core Java
 
Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Core Java introduction | Basics | free course
Core Java introduction | Basics | free course
 
Dev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdetDev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdet
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
 
Core java lessons
Core java lessonsCore java lessons
Core java lessons
 
0 E158 C10d01
0 E158 C10d010 E158 C10d01
0 E158 C10d01
 
Top 10 Java Interview Questions and Answers 2014
Top 10 Java Interview Questions and Answers 2014 Top 10 Java Interview Questions and Answers 2014
Top 10 Java Interview Questions and Answers 2014
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
 
Review Session and Attending Java Interviews
Review Session and Attending Java Interviews Review Session and Attending Java Interviews
Review Session and Attending Java Interviews
 
Core java
Core java Core java
Core java
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1
 
Introduction to java 101
Introduction to java 101Introduction to java 101
Introduction to java 101
 

Similar to Java defining classes

Similar to Java defining classes (20)

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
 
Ruby object model
Ruby object modelRuby object model
Ruby object model
 
Python - object oriented
Python - object orientedPython - object oriented
Python - object oriented
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
Hemajava
HemajavaHemajava
Hemajava
 
Core java by amit
Core java by amitCore java by amit
Core java by amit
 
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and InterfacesUNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
 
Chapter 8 java
Chapter 8 javaChapter 8 java
Chapter 8 java
 
Java basics
Java basicsJava basics
Java basics
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
 
Java/J2EE interview Qestions
Java/J2EE interview QestionsJava/J2EE interview Qestions
Java/J2EE interview Qestions
 
Java session2
Java session2Java session2
Java session2
 
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
 
Chapter 7 java
Chapter 7 javaChapter 7 java
Chapter 7 java
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
 
Java Basics
Java BasicsJava Basics
Java Basics
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptx
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
Lecture 5.pptx
Lecture 5.pptxLecture 5.pptx
Lecture 5.pptx
 
Oops
OopsOops
Oops
 

Recently uploaded

Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 

Recently uploaded (20)

Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 

Java defining classes

  • 1. Defining Classes in JAVA Mehdi Ali Soltani mehdi.alisoltani@gmail.com https://www.linkedin.com/in/mehdi-ali-soltani-315453b7/
  • 2. WHAT IS A CLASS? A class is a prescription for a particular kind of object.
  • 3. Class Properties ➢ Fields: These are variables that store data items that typically differentiate one object of the class from another. They are also referred to as data members of a class. ➢ Methods: These define the operations you can perform for the class so they determine what you can do to, or with, objects of the class. Methods typically operate on the fields the data members of the class.
  • 4. Static and non Static Fields ➢ Non-static fields, also called instance variables : Each object of the class has its own copy of each of the non-static fields or instance variables that appear in the class definition. ➢ Static fields, also called class variables A given class has only one copy of each of its static fields or class variables, and these are shared between and among all the objects of the class
  • 5. Static and non Static Fields Example
  • 6. ➢ instance methods instance methods can be executed only in relation to a particular object MyObject obj = new MyObject();//Create an instance obj.nonstaticMethod();//Refer to the instance's class's code ➢ class methods Class method can be executed even when no objects of a class exist e.g main(), Math.sqrt(), ... Methods in a Class Definition
  • 7. Accessing Variables and Methods ➢ static method double rootPi = Math.sqrt(Math.PI); ➢ Non static method double ballVolume = ball.volume();
  • 8. Final Fields final fields means that the field cannot be modified by the methods in the class final double PI = 3.14; You should provide an initial value for a final field when you declare it.
  • 9. definition of the Sphere class DEFINING CLASSES
  • 10. Basic Structure of a Method
  • 11. Returning from a Method To return a value from a method when its execution is complete use a return statement. return return_value;
  • 12. The Parameter List Parameter and an argument: ➢ A parameter has a name and a type and appears in the parameter list in the definition of a method. A parameter defines the type of value that can be passed to the method when it is called. ➢ An argument is a value that is passed to a method when it is executed, and the value of the argument is referenced by the parameter name during execution of the method
  • 13. Definition of a Method
  • 14. How Argument Values are Passed to a Method All argument values are transferred to a method using what is called the pass-by-value mechanism
  • 15. A method can change an object that is passed as an argument. This is because a variable of a class type contains a reference to an object, not the object itself. Thus, when you use a variable of a class type as an argument to a method, a copy of a reference to the object is passed to the method, not a copy of the object itself. Because a copy of a reference still refers to the same object, the parameter name used in the body of a method refers to the original object that was passed as the argument. Passing Objects to Methods
  • 16. Final Parameters Specifying any of the parameters for a method as final. This has the effect of preventing modification of any argument value that is substituted for the parameter when you call the method.
  • 17. Defining Class Methods Define a class method by adding the keyword static to its definition
  • 18. Defining Class Methods(cont.) Remember that you cannot directly refer to any of the instance variables in the class within a static method. This is because a static method can be executed when no objects of the class have been created, and therefore no instance variables exist.
  • 20. Variable this Every instance method has a variable with the name this that refers to the current object for which the method is being called. The compiler uses this implicitly when your method refers to an instance variable of the class return 4.0/3.0*PI* this.radius *this.radius*this.radius;
  • 21. Sources of Data Available within a Method ➢ Arguments passed to the method, which you refer to by using the parameter names ➢ Data members, both instance variables and class variables, which you refer to by their names ➢ Local variables that you declare in the body of the method ➢ Values that are returned by other methods that are called from within the method
  • 23. CONSTRUCTORS When you create an object of a class, a special kind of method called a constructor is always invoked If you don't define any constructors for your class, the compiler supplies a default constructor in the class, which does nothing
  • 24. Constructor Characteristics ➢ A constructor never returns a value, and you must not specify a return type not even of type void ➢ A constructor always has the same name as the class.
  • 27. Passing Objects to a Method When you pass an object as an argument to a method, the mechanism that applies is called pass-by-reference, because a copy of the reference contained in the variable is transferred to the method, not a copy of the object itself.
  • 28. Passing Objects to a Method
  • 29. The Lifetime of an Object The lifetime of an object is determined by the variable that holds the reference you can reset a variable to refer to nothing by setting its value to null. ball = null; the variable ball no longer refers to an object. The lifetime of an object is determined by whether any variable anywhere in the program still references it. The process of disposing of dead objects is called garbage collection
  • 31. METHOD OVERLOADING Java enables you to define several methods in a class with the same name, as long as each method has a unique set of parameters. Defining two or more methods with the same name in a class is called method overloading Different ways to overload the method 1. By changing number of arguments 2. By changing the data type
  • 34. Multiple Constructors Creating object with different constructors
  • 35. Calling a Constructor from a Constructor One class constructor can call another constructor in the same class in its first executable statement. To refer to another constructor in the same class, use this as the method name, followed by the appropriate arguments between parentheses
  • 36. Calling a Constructor from a Constructor
  • 37. Duplicating Objects Using a Constructor Sphere eightBall = new Sphere(10.0, 10.0, 0.0); Later in your program you want to create a new object newBall, which is identical to the object eightBall. If you write Sphere newBall = eightBall; variable newBall references the same object as eightBall. You don't have a distinct object
  • 38. Duplicating Objects Using a Constructor duplicating an existing object by adding a constructor
  • 39. UNDERSTANDING PACKAGES package is a namespace that organizes a set of related classes and interfaces. Conceptually you can think of packages as being similar to different folders on your computer.
  • 40. Some Important Packages in the Java Library
  • 41. Adding Classes from a Package to Your Program Import by using the import keyword: import package.myclass;
  • 42. CONTROLLING ACCESS TO CLASS MEMBERS Provide you you control the accessibility of class members from outside the class. Using Access Attributes ATTRIBUTE PERMITTED ACCESS No access attribute From methods in any class in the same package. public From methods in any class anywhere as long as the class has been declared as public. private Accessible only from methods inside the class. No access from outside the class at all. protected From methods in any class in the same package and from any subclass anywhere.
  • 43. Allowed Between Classes within the same package
  • 46. Choosing Access Attributes variables in a public class should be private and the methods that are called from outside the class should be public. ➢ For classes in a package that are not public, and therefore not accessible outside the package, it may sometimes be convenient to allow other classes in the package direct access to the data members. ➢ If you have data members that have been specified as final so that their values are fi xed and they are likely to be useful outside the class, you might as well declare them to be public. ➢ You may well have methods in a class that are intended to be used only internally by other methods in the same class. In this case you should specify these as private. ➢ In a class like the standard class Math, which is just a convenient container for utility functions and standard data values, you should make everything public.
  • 47. NESTED CLASSES All the classes you have defined so far have been separate from each other — each stored away in its own source file. You can put the definition of one class inside the definition of another class. The inside class is called a nested class. A nested class can itself have another class nested inside it, if need be.
  • 49. Reference Ivor Horton's Beginning Java®, Java 7 Edition Published by John Wiley & Sons, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 www.wiley.com Copyright © 2011 by John Wiley & Sons, Inc., Indianapolis, Indiana