Enviar pesquisa
Carregar
Week08
•
0 gostou
•
626 visualizações
hccit
Seguir
Tecnologia
Educação
Denunciar
Compartilhar
Denunciar
Compartilhar
1 de 39
Baixar agora
Baixar para ler offline
Recomendados
Cso gaddis java_chapter13
Cso gaddis java_chapter13
mlrbrown
Cso gaddis java_chapter9ppt
Cso gaddis java_chapter9ppt
mlrbrown
4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT
Ajay Chimmani
Object Oriented Programming using C++ Part II
Object Oriented Programming using C++ Part II
Ajit Nayak
Is2215 lecture4 student (1)
Is2215 lecture4 student (1)
dannygriff1
Java data types, variables and jvm
Java data types, variables and jvm
Madishetty Prathibha
Ap Power Point Chpt7
Ap Power Point Chpt7
dplunkett
Vb ch 3-object-oriented_fundamentals_in_vb.net
Vb ch 3-object-oriented_fundamentals_in_vb.net
bantamlak dejene
Recomendados
Cso gaddis java_chapter13
Cso gaddis java_chapter13
mlrbrown
Cso gaddis java_chapter9ppt
Cso gaddis java_chapter9ppt
mlrbrown
4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT
Ajay Chimmani
Object Oriented Programming using C++ Part II
Object Oriented Programming using C++ Part II
Ajit Nayak
Is2215 lecture4 student (1)
Is2215 lecture4 student (1)
dannygriff1
Java data types, variables and jvm
Java data types, variables and jvm
Madishetty Prathibha
Ap Power Point Chpt7
Ap Power Point Chpt7
dplunkett
Vb ch 3-object-oriented_fundamentals_in_vb.net
Vb ch 3-object-oriented_fundamentals_in_vb.net
bantamlak dejene
Chap4java5th
Chap4java5th
Asfand Hassan
Chap5java5th
Chap5java5th
Asfand Hassan
Object Oriented Programming In .Net
Object Oriented Programming In .Net
Greg Sohl
Introduction to OOP concepts
Introduction to OOP concepts
Ahmed Farag
C0 review core java1
C0 review core java1
tam53pm1
Object Oriented Concepts and Principles
Object Oriented Concepts and Principles
deonpmeyer
Concept of Object Oriented Programming
Concept of Object Oriented Programming
Prognoz Technologies Pvt. Ltd.
PCSTt11 overview of java
PCSTt11 overview of java
Archana Gopinath
2.oop concept
2.oop concept
Robbie AkaChopa
Oop concepts classes_objects
Oop concepts classes_objects
William Olivier
Java Notes
Java Notes
Abhishek Khune
Ah java-ppt2
Ah java-ppt2
Haja Abdul Khader A
Eo gaddis java_chapter_06_Classes and Objects
Eo gaddis java_chapter_06_Classes and Objects
Gina Bullock
Chap3java5th
Chap3java5th
Asfand Hassan
Fundamentals of OOP (Object Oriented Programming)
Fundamentals of OOP (Object Oriented Programming)
MD Sulaiman
Object Oriented Programming
Object Oriented Programming
Haris Bin Zahid
Introduction to object oriented programming
Introduction to object oriented programming
Abzetdin Adamov
Introduction to object oriented programming concepts
Introduction to object oriented programming concepts
Ganesh Karthik
Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1
Sakthi Durai
Java Introductie
Java Introductie
mbruggen
Internet
Internet
Rahul Chhatrapati
Java training in delhi
Java training in delhi
APSMIND TECHNOLOGY PVT LTD.
Mais conteúdo relacionado
Mais procurados
Chap4java5th
Chap4java5th
Asfand Hassan
Chap5java5th
Chap5java5th
Asfand Hassan
Object Oriented Programming In .Net
Object Oriented Programming In .Net
Greg Sohl
Introduction to OOP concepts
Introduction to OOP concepts
Ahmed Farag
C0 review core java1
C0 review core java1
tam53pm1
Object Oriented Concepts and Principles
Object Oriented Concepts and Principles
deonpmeyer
Concept of Object Oriented Programming
Concept of Object Oriented Programming
Prognoz Technologies Pvt. Ltd.
PCSTt11 overview of java
PCSTt11 overview of java
Archana Gopinath
2.oop concept
2.oop concept
Robbie AkaChopa
Oop concepts classes_objects
Oop concepts classes_objects
William Olivier
Java Notes
Java Notes
Abhishek Khune
Ah java-ppt2
Ah java-ppt2
Haja Abdul Khader A
Eo gaddis java_chapter_06_Classes and Objects
Eo gaddis java_chapter_06_Classes and Objects
Gina Bullock
Chap3java5th
Chap3java5th
Asfand Hassan
Fundamentals of OOP (Object Oriented Programming)
Fundamentals of OOP (Object Oriented Programming)
MD Sulaiman
Object Oriented Programming
Object Oriented Programming
Haris Bin Zahid
Introduction to object oriented programming
Introduction to object oriented programming
Abzetdin Adamov
Introduction to object oriented programming concepts
Introduction to object oriented programming concepts
Ganesh Karthik
Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1
Sakthi Durai
Mais procurados
(19)
Chap4java5th
Chap4java5th
Chap5java5th
Chap5java5th
Object Oriented Programming In .Net
Object Oriented Programming In .Net
Introduction to OOP concepts
Introduction to OOP concepts
C0 review core java1
C0 review core java1
Object Oriented Concepts and Principles
Object Oriented Concepts and Principles
Concept of Object Oriented Programming
Concept of Object Oriented Programming
PCSTt11 overview of java
PCSTt11 overview of java
2.oop concept
2.oop concept
Oop concepts classes_objects
Oop concepts classes_objects
Java Notes
Java Notes
Ah java-ppt2
Ah java-ppt2
Eo gaddis java_chapter_06_Classes and Objects
Eo gaddis java_chapter_06_Classes and Objects
Chap3java5th
Chap3java5th
Fundamentals of OOP (Object Oriented Programming)
Fundamentals of OOP (Object Oriented Programming)
Object Oriented Programming
Object Oriented Programming
Introduction to object oriented programming
Introduction to object oriented programming
Introduction to object oriented programming concepts
Introduction to object oriented programming concepts
Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1
Destaque
Java Introductie
Java Introductie
mbruggen
Internet
Internet
Rahul Chhatrapati
Java training in delhi
Java training in delhi
APSMIND TECHNOLOGY PVT LTD.
12th Std
12th Std
Kanaga Raj
Java tutorial PPT
Java tutorial PPT
Intelligo Technologies
Class object method constructors in java
Class object method constructors in java
Raja Sekhar
Internet Technology Basics
Internet Technology Basics
National Institute of Mass Communication and Journalism, Ahmedabad
Destaque
(7)
Java Introductie
Java Introductie
Internet
Internet
Java training in delhi
Java training in delhi
12th Std
12th Std
Java tutorial PPT
Java tutorial PPT
Class object method constructors in java
Class object method constructors in java
Internet Technology Basics
Internet Technology Basics
Semelhante a Week08
Ch 2 Library Classes.pptx
Ch 2 Library Classes.pptx
KavitaHegde4
Ch 2 Library Classes.pdf
Ch 2 Library Classes.pdf
KavitaHegde4
React-Native Lecture 11: In App Storage
React-Native Lecture 11: In App Storage
Kobkrit Viriyayudhakorn
Cso gaddis java_chapter6
Cso gaddis java_chapter6
RhettB
Introduction to C++ Class & Objects. Book Notes
Introduction to C++ Class & Objects. Book Notes
DigitalDsms
Concepts for Object Oriented Databases.ppt
Concepts for Object Oriented Databases.ppt
nafsigenet
Tools-and-Techniques-for-Basic-Administration-vFinal3.pptx
Tools-and-Techniques-for-Basic-Administration-vFinal3.pptx
indupriya93
Chapter 4 Writing Classes
Chapter 4 Writing Classes
DanWooster1
C++ training
C++ training
PL Sharma
07slide.ppt
07slide.ppt
NuurAxmed2
Bn1038 demo pega
Bn1038 demo pega
conline training
Week07
Week07
hccit
Lecture 5.pptx
Lecture 5.pptx
AshutoshTrivedi30
Pi j2.3 objects
Pi j2.3 objects
mcollison
implementing oop_concept
implementing oop_concept
Amit Gupta
Objective-C for iOS Application Development
Objective-C for iOS Application Development
Dhaval Kaneria
Cso gaddis java_chapter6
Cso gaddis java_chapter6
mlrbrown
7. Pointers and Virtual functions final -3.pptx
7. Pointers and Virtual functions final -3.pptx
Abhishekkumarsingh630054
Oops Concept Java
Oops Concept Java
Kamlesh Singh
Constructors and Method Overloading
Constructors and Method Overloading
Ferdin Joe John Joseph PhD
Semelhante a Week08
(20)
Ch 2 Library Classes.pptx
Ch 2 Library Classes.pptx
Ch 2 Library Classes.pdf
Ch 2 Library Classes.pdf
React-Native Lecture 11: In App Storage
React-Native Lecture 11: In App Storage
Cso gaddis java_chapter6
Cso gaddis java_chapter6
Introduction to C++ Class & Objects. Book Notes
Introduction to C++ Class & Objects. Book Notes
Concepts for Object Oriented Databases.ppt
Concepts for Object Oriented Databases.ppt
Tools-and-Techniques-for-Basic-Administration-vFinal3.pptx
Tools-and-Techniques-for-Basic-Administration-vFinal3.pptx
Chapter 4 Writing Classes
Chapter 4 Writing Classes
C++ training
C++ training
07slide.ppt
07slide.ppt
Bn1038 demo pega
Bn1038 demo pega
Week07
Week07
Lecture 5.pptx
Lecture 5.pptx
Pi j2.3 objects
Pi j2.3 objects
implementing oop_concept
implementing oop_concept
Objective-C for iOS Application Development
Objective-C for iOS Application Development
Cso gaddis java_chapter6
Cso gaddis java_chapter6
7. Pointers and Virtual functions final -3.pptx
7. Pointers and Virtual functions final -3.pptx
Oops Concept Java
Oops Concept Java
Constructors and Method Overloading
Constructors and Method Overloading
Mais de hccit
Snr ipt 10_syll
Snr ipt 10_syll
hccit
Snr ipt 10_guide
Snr ipt 10_guide
hccit
3 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr12
hccit
3 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr11
hccit
10 ict photoshop_proj_2014
10 ict photoshop_proj_2014
hccit
Photoshop
Photoshop
hccit
Flash
Flash
hccit
University partnerships programs email
University partnerships programs email
hccit
Griffith sciences pathway programs overview
Griffith sciences pathway programs overview
hccit
Griffith info tech brochure
Griffith info tech brochure
hccit
Pm sql exercises
Pm sql exercises
hccit
Repairs questions
Repairs questions
hccit
Movies questions
Movies questions
hccit
Australian birds questions
Australian birds questions
hccit
Section b
Section b
hccit
B
B
hccit
A
A
hccit
Section a
Section a
hccit
Ask manual rev5
Ask manual rev5
hccit
Case study report mj
Case study report mj
hccit
Mais de hccit
(20)
Snr ipt 10_syll
Snr ipt 10_syll
Snr ipt 10_guide
Snr ipt 10_guide
3 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr11
10 ict photoshop_proj_2014
10 ict photoshop_proj_2014
Photoshop
Photoshop
Flash
Flash
University partnerships programs email
University partnerships programs email
Griffith sciences pathway programs overview
Griffith sciences pathway programs overview
Griffith info tech brochure
Griffith info tech brochure
Pm sql exercises
Pm sql exercises
Repairs questions
Repairs questions
Movies questions
Movies questions
Australian birds questions
Australian birds questions
Section b
Section b
B
B
A
A
Section a
Section a
Ask manual rev5
Ask manual rev5
Case study report mj
Case study report mj
Último
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
ThousandEyes
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Zilliz
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
apidays
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
apidays
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
sammart93
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
Dropbox
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
Anna Loughnan Colquhoun
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
Khem
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
Andrey Devyatkin
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
Remote DBA Services
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
Product Anonymous
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
Overkill Security
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
Zilliz
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
MIND CTI
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
MadyBayot
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
Khushali Kathiriya
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
debabhi2
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
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
Último
(20)
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
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, ...
Week08
1.
Week 8 Classes &
Objects: Writing Classes, Creating and Using Objects
2.
Copyright Warning
COMMONWEALTH OF AUSTRALIA Copyright Regulations 1969 WARNING This material has been copied and communicated to you by or on behalf of Bond University pursuant to Part VB of the Copyright Act 1968 (the Act). The material in this communication may be subject to copyright under the Act. Any further copying or communication of this material by you may be the subject of copyright protection under the Act. Do not remove this notice. © 2004 Pearson Addison-Wesley. All rights reserved 4-2
3.
Classes & Objects? •
Last time, we looked at the idea of classes to group together data of different types about something • A Java class provides a template for the things in the class, e.g. all bank accounts • An object, built from the class template, represents a single thing, i.e. one account • Each object in the class will have the same set of attributes, but each object can have different values for the attributes © 2004 Pearson Addison-Wesley. All rights reserved 4-3
4.
Why Classes &
Objects? • Prime purpose: to group together data items related to one thing • Also: we can include methods in the class, so that the data items can be manipulated in a consistent way • Also: we can protect the data items, so that the only access to them is through the methods provided • This ensures that, despite bugs or malicious code, our data remains intact and useful e.g. what if someone tried to withdraw money from a bank account without knowing the PIN? © 2004 Pearson Addison-Wesley. All rights reserved 4-4
5.
Writing Classes • The
programs we’ve written in previous examples have used classes defined in the Java standard class library • Now we will begin to design programs that rely on classes that we write ourselves • The class that contains the main() method is just the starting point of a program • True object-oriented programming is based on defining classes that represent objects with well- defined characteristics and functionality © 2004 Pearson Addison-Wesley. All rights reserved 4-5
6.
Structure of A
Class • A class can contain data declarations and method declarations int size, weight; Data declarations char category; Method declarations © 2004 Pearson Addison-Wesley. All rights reserved 4-6
7.
Classes: State &
Behaviour • The values of the attribute data define the state of an object created from the class • The functionality of the methods define the behaviors of the object • Given a class, we can create or construct an object from the class, with its own state • Then, the object uses its own methods to manipulate its attributes © 2004 Pearson Addison-Wesley. All rights reserved 4-7
8.
Designing the BankAccount
Class • Let's go back to the BankAccount class from last time. Here is what we designed so far: public class BankAccount { int accountNumber; double balance; int PinNumber; } • These are the attributes, or the state, that each object constructed from the class will have. • The first method we need to write is a constructor method. © 2004 Pearson Addison-Wesley. All rights reserved 4-8
9.
Constructors •
A constructor method is a special method that is used to set up an object when it is initially created from the class template • A constructor has the same name as the class • It normally takes as inputs the values that will be put into the object's attributes public BankAccount(int acct, double bal, int pin) { accountNumber= acct; balance= bal; PinNumber= pin; } © 2004 Pearson Addison-Wesley. All rights reserved 4-9
10.
Constructors • Note that
we can use the names of the attribute variables • That's because the constructor method makes a new object, and each object has its own attribute variables • Scope rule: if a variable isn't declared in a method, look for it as an attribute variable in the class • We can write several different constructors, as long as the list of input parameters is different for each one. • Let's write a constructor where no balance is given. What should the balance be set to? © 2004 Pearson Addison-Wesley. All rights reserved 4-10
11.
Multiple Constructors
public BankAccount(int acct, int PinNumber) { accountNumber= acct; balance= 0.0; this.PinNumber= PinNumber; } • We set the balance to 0.0, thus keeping the object's attributes safe and useful • Note: conflict between the input parameter's name and the name of the attribute • To resolve this: we use this. to specify the attribute in this object © 2004 Pearson Addison-Wesley. All rights reserved 4-11
12.
Making An Object
in Bluej • Compile, and right-click on the class file • Choose one of the constructor methods • Fill in the input parameters & click Ok • The object appears down the bottom © 2004 Pearson Addison-Wesley. All rights reserved 4-12
13.
Inspecting An Object
in Bluej • Right-click on the object, and choose Inspect • Bluej shows you the values of the attributes • This creating/inspecting is only useful when testing the classes that you write © 2004 Pearson Addison-Wesley. All rights reserved 4-13
14.
The toString() Method •
We need to add more methods to the class, to make it useful • All classes that represent objects should define a toString() method: Java expects this • The toString() method returns a String that represents the object in some way • It is called automatically when an object is concatenated to a string or when it is passed to the println() method • It's up to you, the designer, to think of how to best represent the object's attributes as a string © 2004 Pearson Addison-Wesley. All rights reserved 4-14
15.
toString() for BankAccount
public String toString() { return(“Account “ + accountNumber + “, $” + balance); } • Once you have constructed an object with Bluej, you can right-click on it, and run any of its methods © 2004 Pearson Addison-Wesley. All rights reserved 4-15
16.
Gettor or Accessor
Methods • Accessor methods allow external access to the object's attributes • They also protect the object from unauthorised use • For the BankAccount class: int getAccountNumber() int getBalance(int pin) no method to get the PIN: user should know it • Note that getBalance() requires knowledge of the PIN: an example of the method protecting the data kept inside the object • Again, once an object is created, Bluej allows you to run any of its methods on itself © 2004 Pearson Addison-Wesley. All rights reserved 4-16
17.
Settor or Mutator
Methods • Settor methods allow the object's attributes to be set or updated • Again, they also protect the object from being corrupted • For the BankAccount class: boolean deposit(double amount) boolean withdraw(int pin, double amount) boolean setPIN(int oldpin, int newpin) • Anybody can deposit money, only people with the PIN can withdraw or set a new PIN • All methods in this example return true if the operation succeeded. • Note: all methods check their input values! • 2004 Pearson Addison-Wesley. All rights reserved © Note the strict requirements for withdraw() 4-17
18.
Instance Data • The
balance variable in the BankAccount class is called instance data because each instance (object) that is created has its own version of it • A class declares the type of the data, but it does not reserve any memory space for the variables • Every time a BankAccount object is created, a new balance variable is created as well • The objects of a class share the methods in the class, but each object has its own instance variables • That's the only way two objects can have different states © 2004 Pearson Addison-Wesley. All rights reserved 4-18
19.
Scope and Local
Variables • The scope of a variable is the area in a program in which that variable can be referenced (used) • Variables declared at the class level can be referenced by all methods in that class • Variables declared within a method can be used only in that method • Variables declared within a method are called local variables • In the BankAccount class, the variable interest is declared inside the calculateInterest() method - it is local to that method and cannot be referenced anywhere else © 2004 Pearson Addison-Wesley. All rights reserved 4-19
20.
Encapsulation • We can
take one of two views of an object: internal - the details of the variables and methods of the class that defines it external - the services that an object provides and how the object interacts with the rest of the system • From the external view, an object is an encapsulated entity, providing a set of specific services accessor methods, settor methods etc. • These services define the interface to the object © 2004 Pearson Addison-Wesley. All rights reserved 4-20
21.
Encapsulation • One object
(called the client) may use another object for the services it provides • The client of an object may request its services (call its methods), but it should not have to be aware of how those services are accomplished • Any changes to the object's state (its variables) should be made by that object's methods • We should make it difficult, if not impossible, for a client to access an object’s variables directly • That is, an object should be self-governing © 2004 Pearson Addison-Wesley. All rights reserved 4-21
22.
Encapsulation • An encapsulated
object can be thought of as a black box -- its inner workings are hidden from the client • The client invokes the interface methods of the object, which manages the instance data Client Methods Data © 2004 Pearson Addison-Wesley. All rights reserved 4-22
23.
Visibility Modifiers • In
Java, we accomplish encapsulation through the appropriate use of visibility modifiers • A modifier is a Java reserved word that specifies particular characteristics of a method or data • Members of a class that are declared with public visibility can be referenced anywhere • Members of a class that are declared with private visibility can be referenced only by the methods within that class © 2004 Pearson Addison-Wesley. All rights reserved 4-23
24.
Visibility Modifiers • Public
variables violate encapsulation because they allow the client to “reach in” and modify the values directly; this is usually very bad • Therefore instance variables should not be declared with public visibility • It is acceptable to give a constant public visibility, which allows it to be used outside of the class • Public constants do not violate encapsulation because, although the client can access it, its value cannot be changed © 2004 Pearson Addison-Wesley. All rights reserved 4-24
25.
Visibility Modifiers • Methods
that provide the object's services are declared with public visibility so that they can be invoked by clients • Public methods are also called service methods • A method created simply to assist a service method is called a support method • Since a support method is not intended to be called by a client, it should not be declared with public visibility © 2004 Pearson Addison-Wesley. All rights reserved 4-25
26.
Visibility Modifiers
public private Violate Enforce Variables encapsulation encapsulation Support other Provide services Methods methods in the to clients class © 2004 Pearson Addison-Wesley. All rights reserved 4-26
27.
Accessors and Mutators •
Because instance data is private, a class usually provides services to access and modify data values • An accessor method returns the current value of a variable • A mutator method changes the value of a variable • The names of accessor and mutator methods take the form getX and setX, respectively, where X is the name of the value • They are sometimes called “gettors” and “settors” © 2004 Pearson Addison-Wesley. All rights reserved 4-27
28.
Mutator Restrictions • The
use of mutators gives the class designer the ability to restrict a client’s options to modify an object’s state • A mutator is often designed so that the values of variables can be set only within particular limits • For example, the setFaceValue mutator of the Die class should have restricted the value to the valid range (1 to MAX) • We’ll see in Chapter 5 how such restrictions can be implemented © 2004 Pearson Addison-Wesley. All rights reserved 4-28
29.
Methods Calling Method •
Methods in your class are normal Java methods like we have seen before • They can have their own variables, and have normal Java control structures • Methods can call other methods • If the other method is in the same class, we can simply use its name • If the other method is in a different class, or is a method inside an object, we have to write the name of the class/object, dot, then the method name © 2004 Pearson Addison-Wesley. All rights reserved 4-29
30.
Method Control Flow •
If the called method is in the same class, only the method name is needed compute myMethod myMethod(); © 2004 Pearson Addison-Wesley. All rights reserved 4-30
31.
Method Control Flow •
The called method is often part of another class or object main doIt helpMe obj.doIt(); helpMe(); © 2004 Pearson Addison-Wesley. All rights reserved 4-31
32.
Using Objects in
Java • We have shown you how to create objects with Bluej • This is only for testing. Normally, you would write a client program that uses a class to create objects from that class • For example, the MyBank program is an example of a program that makes and uses BankAccount objects • WARNING!!! When you declare BankAccount userAcct; this DOES NOT create an object! • It only declares the name of an object in the future • You must still construct an object for it to be created © 2004 Pearson Addison-Wesley. All rights reserved 4-32
33.
Constructing Objects in
Java • Use the new command to construct an object; provide a set of parameters that will match one of the constructor methods, e.g computerAcct= new BankAccount(6475, 1123); • Java runs the constructor, and a new object is stored in the computer's memory. • It doesn't appear in the Bluej window. • To see it, use the debugger to inspect the computerAcct variable • You can pass any parameters to a constructor: literal constants, variables holding values passed in by the user etc. © 2004 Pearson Addison-Wesley. All rights reserved 4-33
34.
Using Objects in
Java • Once an object is constructed, we can use any of the methods from the class, via the object. object's name.method(parameters); • For example: userAccount.calculateInterest(0.08); • In fact, you have been constructing and using objects already: Scanner scan = new Scanner(System.in); question= scan.nextLine(); © 2004 Pearson Addison-Wesley. All rights reserved 4-34
35.
The static Keyword •
A static method is a special method that does not require an object to invoke • It is used when a method is not specific to any object • A static method is invoked through the name of the class rather than the name of an object of that class • For example, Math.max(int, int) returns the value of the larger of two integer arguments • Examples of use: big = Math.max(a, b); System.out.println( big ); • All of your main() programs have been static, so you could run them without objects © 2004 Pearson Addison-Wesley. All rights reserved 4-35
36.
Classes: Not Just
Real Things • Classes are just to group related data together, and to provide a set of methods to correctly manipulate that data • A Class, and its objects, don't have to represent real things; just a group of related data • Each pixel on a screen has a <red,green,blue> colour, and possibly a transparency percentage public class Pixel { byte red,green,blue; byte transparency; } © 2004 Pearson Addison-Wesley. All rights reserved 4-36
37.
Strings are Objects •
Strings in Java are objects, and there is a String class that provides a useful set of methods to manipulate Strings • Each string literal (enclosed in double quotes) represents a String object • Once a String object has been created, neither its value nor its length can be changed • However, several methods of the String class return new String objects that are modified versions of the original © 2004 Pearson Addison-Wesley. All rights reserved 4-37
38.
Useful String Methods •
See the on-line String class documentation for more details charAt() - Get a char at a particular position compareTo() - Compare a string to another one endsWith() - See if a string ends with a suffix indexOf() - Find first position of a char in string length() - Returns the string's length replace() - Replaces all of ch1 with ch2 in string trim() - Remove leading/trailing whitespace © 2004 Pearson Addison-Wesley. All rights reserved 4-38
39.
The Last Slide! •
Types that start with lowercase in Java are primitive types, not classes/objects byte, short, int, long, char, float, double, boolean • Any type that starts with an uppercase letter is a class, and you must construct objects from the class, and use class methods • The String class is one exception, you can do String message = “This is a message”; • Just as we can have arrays or primitive types, we can also have arrays of objects. To use the method of one object in the array, we do bankaccountList[8].withdraw(1234, 75.00); array name index method © 2004 Pearson Addison-Wesley. All rights reserved 4-39
Baixar agora