Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Full Transcript

Chapter 3: Using Methods, Classes, and Objects Objectives Learn about method calls and placement Identify the parts of a method Add parameters to methods Create methods that return values Learn about classes and objects Create a cla...

Chapter 3: Using Methods, Classes, and Objects Objectives Learn about method calls and placement Identify the parts of a method Add parameters to methods Create methods that return values Learn about classes and objects Create a class Create instance methods in a class 2 Java Programming, Eighth Edition Objectives (cont’d.) Declare objects and use their methods Create constructors Appreciate classes as data types 3 Java Programming, Eighth Edition Understanding Method Calls and Placement Method – A program module – Contains a series of statements – Carries out a task Execute a method – Invoke or call from another method Calling method (client method) – Makes a method call Called method – Invoked by a calling method 4 Java Programming, Eighth Edition Understanding Method Calls and Placement (cont’d.) 5 Java Programming, Eighth Edition Understanding Method Calls and Placement (cont’d.) main() method executes automatically Other methods are called as needed 6 Java Programming, Eighth Edition Understanding Method Calls and Placement (cont’d.) 7 Java Programming, Eighth Edition Understanding Method Construction A method must include: – Method header Also called a declaration – Method body Between a pair of curly braces Contains the statements that carry out the work Also called implementation 8 Java Programming, Eighth Edition Understanding Method Construction (cont’d.) 9 Java Programming, Eighth Edition Understanding Method Construction (cont’d.) The method header contains: – Optional access specifiers – A return type – An identifier – Parentheses Might contain data to be sent to the method Place the entire method within the class that will use it – Not within any other method 10 Java Programming, Eighth Edition Access Specifiers Can be public, private, protected , or package public access allows use by any other class Also called access modifiers Methods most commonly use public access 11 Java Programming, Eighth Edition Access Specifiers (cont’d.) 12 Java Programming, Eighth Edition Group Task Write a program that can calculate the total weekly salary of an employee at company XYZ. You are told that the person earns R250 per hour and works for 5 days per week. The person works for 8 hours per day. Your program should use a method and display the total salary. Please note that you are supposed to write a program that does the calculation and produce the answer 13 Java Programming, Eighth Edition 14 Java Programming, Eighth Edition Return Type Describes the type of data the method sends back to the calling method If no data is returned to the method, the return value is void 15 Java Programming, Eighth Edition Return Type (cont’d.) 16 Java Programming, Eighth Edition Method Name Can be any legal identifier – Must be one word – No embedded spaces – Cannot be a Java keyword 17 Java Programming, Eighth Edition Method Name (cont’d.) 18 Java Programming, Eighth Edition Parentheses Every method header contains a set of parentheses that follow the identifier May contain data to be sent to the method Fully qualified identifier – A complete name that includes the class 19 Java Programming, Eighth Edition Parentheses (cont’d.) 20 Java Programming, Eighth Edition Adding Parameters to Methods Arguments – Data items you use in a call to a method Parameters – Data items received by the method Implementation hiding – Encapsulation of method details within a class – The calling method needs to understand only the interface to the called method – Interface The only part of a method that the client sees or with which it interacts 21 Java Programming, Eighth Edition Creating a Method That Receives a Single Parameter Define the following: – Optional access specifiers – Return type for the method – Method name – Parameter type – Local name for the parameter 22 Java Programming, Eighth Edition Creating a Method That Receives a Single Parameter (cont’d.) 23 Java Programming, Eighth Edition Creating a Method That Receives a Single Parameter (cont’d.) Local variable – Known only within the boundaries of the method – Each time the method executes: The variable is redeclared A new memory location large enough to hold the type is set up and named 24 Java Programming, Eighth Edition Creating a Method That Receives a Single Parameter (cont’d.) 25 Java Programming, Eighth Edition Creating a Method That Requires Multiple Parameters A method can require more than one parameter List the arguments within the call to the method – Separate with commas Call a method – Arguments sent to the method must match the parameters listed in the method declaration by: Number Type 26 Java Programming, Eighth Edition Creating a Method That Requires Multiple Parameters (cont’d.) 27 Java Programming, Eighth Edition Creating a Method That Requires Multiple Parameters (cont’d.) 28 Java Programming, Eighth Edition Creating a Method That Requires Multiple Parameters (cont’d.) 29 Java Programming, Eighth Edition Creating Methods That Return Values return statement – Causes a value to be sent from the called method back to the calling method The return type can be any type used in Java – Primitive types – Class types – void Returns nothing Method’s type – A method’s return type 30 Java Programming, Eighth Edition Creating Methods That Return Values (cont’d.) 31 Java Programming, Eighth Edition Creating Methods That Return Values (cont’d.) Unreachable statements (dead code) – Logical flow leaves the method at the return statement – Can never execute Causes a compiler error 32 Java Programming, Eighth Edition Chaining Method Calls Any method might call any number of other methods Method acts as a black box – Do not need to know how it works – Just call and use the result 33 Java Programming, Eighth Edition Chaining Method Calls (cont’d.) 34 Java Programming, Eighth Edition Learning About Classes and Objects Every object is a member of a class Is-a relationships – An object “is a” concrete example of the class – The zoo’s shark “is a” Fish Instantiation – Shark is an instantiation of the Fish class Reusability 35 Java Programming, Eighth Edition Learning About Classes and Objects (cont’d.) Methods are often called upon to return a piece of information to the source of the request Class client or class user – An application or a class that instantiates objects of another prewritten class 36 Java Programming, Eighth Edition Creating a Class Assign a name to the class Determine what data and methods will be part of the class Create a class header with three parts: – An optional access modifier – The keyword class – Any legal identifier for the name of the class public class – Accessible by all objects 37 Java Programming, Eighth Edition Creating a Class (cont’d.) 38 Java Programming, Eighth Edition Creating a Class (cont’d.) Extended – To be used as a basis for any other class Data fields – Variables declared within a class but outside of any method Instance variables – Nonstatic fields given to each object 39 Java Programming, Eighth Edition Creating a Class (cont’d.) Private access for fields – No other classes can access the field’s values – Only methods of the same class are allowed to use private variables Information hiding Most class methods are public 40 Java Programming, Eighth Edition Creating Instance Methods in a Class Classes contain methods – Mutator methods Set or change field values – Accessor methods Retrieve values – Nonstatic methods Instance methods “Belong” to objects Typically declare nonstatic data fields static class variables are not instance variables 41 Java Programming, Eighth Edition 42 Java Programming, Eighth Edition 43 Java Programming, Eighth Edition Creating Instance Methods in a Class (cont’d.) 44 Java Programming, Eighth Edition Organizing Classes Place data fields in logical order – At the beginning of a class – List the fields vertically Data fields and methods may be placed in any order within a class – It’s common to list all data fields first – Names and data types can be seen before reading the methods that use the data fields 45 Java Programming, Eighth Edition Organizing Classes (cont’d.) 46 Java Programming, Eighth Edition Organizing Classes (cont’d.) (continued) 47 Java Programming, Eighth Edition Declaring Objects and Using Their Methods Declaring a class does not create any actual objects To create an instance of a class: – Supply a type and an identifier – Allocate computer memory for the object – Use the new operator Employee someEmployee; someEmployee = new Employee(); or Employee someEmployee = new Employee(); 48 Java Programming, Eighth Edition Declaring Objects and Using Their Methods (cont’d.) Reference to the object – The name for a memory address where the object is held Constructor method – A method that creates and initializes class objects – You can write your own constructor methods – Java writes a constructor when you don’t write one – The name of the constructor is always the same as the name of the class whose objects it constructs 49 Java Programming, Eighth Edition Declaring Objects and Using Their Methods (cont’d.) After an object is instantiated, its methods can be accessed using: – The object’s identifier – A dot – A method call 50 Java Programming, Eighth Edition Declaring Objects and Using Their Methods (cont’d.) 51 Java Programming, Eighth Edition Understanding Data Hiding Data hiding using encapsulation – Data fields are usually private – The client application accesses them only through public interfaces set method – Controls the data values used to set a variable get method – Controls how a value is retrieved 52 Java Programming, Eighth Edition An Introduction to Using Constructors Employee chauffeur = new Employee(); – Actually a calling method named Employee() Default constructors – Require no arguments – Created automatically by a Java compiler For any class Whenever you do not write a constructor 53 Java Programming, Eighth Edition An Introduction to Using Constructors (cont’d.) The default constructor provides specific initial values to an object’s data fields – Numeric fields Set to 0 (zero) – Character fields Set to Unicode ‘\u0000’ – Boolean fields Set to false – Nonprimitive object fields Set to null 54 Java Programming, Eighth Edition An Introduction to Using Constructors (cont’d.) A constructor method: – Must have the same name as the class it constructs – Cannot have a return type – public access modifier 55 Java Programming, Eighth Edition An Introduction to Using Constructors (cont’d.) 56 Java Programming, Eighth Edition Understanding That Classes Are Data Types Classes you create become data types – Often referred to as abstract data types (ADTs) Implementation is hidden and accessed through public methods – Programmer-defined data type Not built into the language Declare an object from one of your classes – Provide the type and identifier 57 Java Programming, Eighth Edition You Do It Creating a static Method that Requires No Arguments and Returns No Values Creating static Methods that Accept Arguments and Return a Value Creating a Class that Contains Instance Fields and Methods Declaring and Using Objects Adding a Constructor to a Class Understanding that Classes are Data Types 58 Java Programming, Eighth Edition Don’t Do It Don’t place a semicolon at the end of a method header Don’t think “default constructor” means only the automatically supplied constructor Don’t think that a class’s methods must: – Accept its own fields’ values as parameters – Return values to its own fields Don’t create a class method that has a parameter with the same identifier as a class field 59 Java Programming, Eighth Edition Summary Method – A series of statements that carry out a task A declaration includes the parameter type and local name for a parameter You can pass multiple arguments to methods – Has a return type Class objects – Have attributes and methods associated with them Instantiate objects that are members of a class 60 Java Programming, Eighth Edition Summary (cont’d.) Constructor – A method establishes an object and provides specific initial values for an object’s data fields Everything is an object – Every object is a member of a more general class Implementation hiding, or encapsulation – private data fields – public access methods 61 Java Programming, Eighth Edition

Use Quizgecko on...
Browser
Browser