Download presentation
Presentation is loading. Please wait.
Published byMalcolm West Modified over 9 years ago
1
1 Java Programming Using Methods, Classes, and Objects
2
2 Topics: Methods with no arguments,with no arguments, a single argument,a single argument, multiple argumentsmultiple arguments with return valueswith return values Class concepts Create a classCreate a class Use instance methodsUse instance methods Declare objectsDeclare objects Organize classesOrganize classes Use constructorsUse constructors
3
3 Method A method is a series of statements that carry out a task Any class can contain an unlimited number of methods
4
4 Methods Methods must include: A declaration An opening curly brace A body A closing brace
5
5 Methods Method declarations must contain: Optional access modifiers The return type for the method The method name An opening parenthesis An optional list of method arguments A closing parenthesis
6
6 Access Modifiers Access modifiers for a method can be: public- most often methods are given public access private protected static
7
7 Access Modifiers public- Endowing a method with public access means any class can use it static- Any method that can be used from anywhere within the class requires the keyword modifier static
8
8 Creating Methods that Require a Single Argument Arguments- Are communications to a method Implementation hiding- Allows that the invoking program must know the name of the method and what type of information to send it, but the program does not need to know how the method works
9
9 Creating Methods that Require a Single Argument The method declaration must include: The type of the argument A local name for the argument For example:For example: public void predictRaise(double moneyAmount)
10
10 Calling a Method Can use either argument: ConstantConstant VariableVariable predictRaise(472.55) predictRaise(mySalary)
11
11 Creating Methods that Require Multiple Arguments Methods can require more than one argument Pass multiple arguments by: Listing the arguments in the call to the methodListing the arguments in the call to the method Separating them with commasSeparating them with commas The declaration for a method that receives two or more arguments must list the type for each argument separately
12
12 A Method’s Return Type The return type is known as the method’s type For example: public static void nameAndAddress() This method is public and returns no valueThis method is public and returns no value public static String nameAndAddress() This method returns a string (with name and address)This method returns a string (with name and address)
13
13 Return Statement The return statement is the last statement in a method Usually you use the returned value, but this is not required
14
14 Overloading a Method Overloading: Involves using one term to indicate diverse meanings Writing multiple methods with the same name, but with different arguments Overloading a Java method means you write multiple methods with a shared name
15
15 Overloaded methods Methods can be overloaded to support different types of data Overloaded methods have the same name and return type (the latter is often forgotten)Overloaded methods have the same name and return type (the latter is often forgotten) But the number and type of arguments can be changed to support different cases/scenariosBut the number and type of arguments can be changed to support different cases/scenarios For exampleFor example float calculateRaise(float Salary, float Raise_Amount ); 2 nd argument represents raise in $ (float)2 nd argument represents raise in $ (float) float calculateRaise(float Salary, int Percent_Amount); 2 nd argument represents raise in percent (integer)2 nd argument represents raise in percent (integer) float calculateRaise(float Salary); No 2 nd argument, standard (constant raise)No 2 nd argument, standard (constant raise)
16
16 Learning about Ambiguity When you overload a method you run the risk of ambiguity An ambiguous situation is one in which the compiler cannot determine which method to useAn ambiguous situation is one in which the compiler cannot determine which method to use Examples?Examples?
17
17 Overloading Example static float calculateRaise(float empSalary, float payRaise) { return empSalary + payRaise; } static float calculateRaise(float empSalary, int payRaise) { return empSalary * (1 + (float)payRaise/100); } public static void main(String[] arg) {// why need “f” after constant System.out.println("1: " + calculateRaise(100000.00f, 3000.00f)); System.out.println("1: " + calculateRaise(100000.00f, 3000.00f)); System.out.println("1: " + calculateRaise(100000.00f, 10)); System.out.println("1: " + calculateRaise(100000.00f, 10)); System.out.println("1: " + calculateRaise(100000, 10.0)); //doesn’t work System.out.println("1: " + calculateRaise(100000, 10.0)); //doesn’t work}
18
18 Class Concepts In object-oriented programming: Everything is an object An object is an instantiation of a class, or a tangible example of a class Every object is a member of a class Your desk is an object and is a member of the Desk classYour desk is an object and is a member of the Desk class These statements represent is-a relationshipsThese statements represent is-a relationships
19
19 Class Concepts The concept of a class is useful because: The concept of a class is useful because: Objects inherit attributes from classesObjects inherit attributes from classes All objects have predictable attributes because they are members of certain classesAll objects have predictable attributes because they are members of certain classes You must: You must: Create the classes of objects from which objects will be instantiatedCreate the classes of objects from which objects will be instantiated Write other classes to use the objectsWrite other classes to use the objects Class Client or Class User-A program or class that instantiates objects of another prewritten class Class Client or Class User-A program or class that instantiates objects of another prewritten class
20
20 Creating a Class You must: Assign a name to the class Determine what data and methods will be part of the class To begin, create a class header with three parts: An optional access modifier The keyword class Any legal identifier you choose for the name of the class The define the class contents Then add a open and close brace Add the attributes (fields) and actions (methods) to the class
21
21 Access modifiers for Classes Access modifiers include: public This is the most used modifierThis is the most used modifier Most liberal form of accessMost liberal form of access Can be extended or used as the basis for other classesCan be extended or used as the basis for other classes final- used only under special circumstances abstract- used only under special circumstances
22
22 Access modifiers for Fields and Methods Private (default for fields) Public (default for methods) Static Final
23
23 Field Modifiers Private No other classes can access a field’s valuesNo other classes can access a field’s values Only methods of the same class are allowed to set, get, or otherwise use private variablesOnly methods of the same class are allowed to set, get, or otherwise use private variables Highest level of securityHighest level of security Also called information hidingAlso called information hiding Provides a means to control outside access to your data
24
24 Using Instance Methods Methods used with object instantiations are called instance methods You can call class methods without creating an instance of the class.You can call class methods without creating an instance of the class. Instance methods require an instantiated object.Instance methods require an instantiated object.
25
25 Declaring Objects To declare an object: Supply a type and an identifier Allocate computer memory for the object Use the new operatorUse the new operator
26
26 Organizing Classes Most programmers place data fields in some logical order at the beginning of a class For example, use a unique identifier for each employeeFor example, use a unique identifier for each employee empNum Last names and first names are organized togetherLast names and first names are organized together
27
27 Using Constructor Methods Constructor methods- Methods that establish an object Employee chauffer = new Employee(); Calls a method named Employee() that is provided by the Java compiler Methods are commonly overloaded to provide various ways to initialize an object Employee chauffer = new Employee(“Mike Elm”); Employee chauffer = new Employee(“Mike Elm”, 2320);
28
28 ADVANCED TOPICS
29
29 Advanced Topics: Understand blocks and scope Learn about ambiguity Send arguments to constructors Overload constructors Learn about the this reference Work with constants Use automatically imported, prewritten constants and methods Use prewritten imported methods
30
30 Understanding Blocks Blocks-Within any class or method, the code between a pair of curly braces Outside block- The first block, begins immediately after the method declaration and ends at the end of the methodOutside block- The first block, begins immediately after the method declaration and ends at the end of the method Inside block- The second block, contained within the second pair of curly bracesInside block- The second block, contained within the second pair of curly braces The inside block is nested within the outside blockThe inside block is nested within the outside block
31
31 Understanding Scope The portion of a program within which you can reference a variable A variable comes into existence, or comes into scope, when you declare it A variable ceases to exist, or goes out of scope, at the end of the block in which it is declared
32
32 public class Test { public static void main(String[] args) throws Exception { while (true) { int Count = 10; …. …. Count++; // this is ok Count++; // this is ok } for(int i = 0; i < MAX_NUM; i++) { Count++; // this will generate an error, why? Count++; // this will generate an error, why? } } // end of main }//end of class Test
33
33 Overriding a Method or Variable If you declare a variable within a class, and use the same variable name within a method of the class, then the variable used inside the method takes precedence, or overrides, the first variable In Java you can override variables and methods Variable overriding is confusing and should be avoidedVariable overriding is confusing and should be avoided Method overriding is useful and necessaryMethod overriding is useful and necessary
34
34 Constructors Java automatically provides a constructor method when you create a class Programmers can write their own constructor methods Programmers can also write constructors that receive arguments Such arguments are often used for initialization purposes when values of objects might varySuch arguments are often used for initialization purposes when values of objects might vary
35
35 Overloading Constructors If you create a class from which you instantiate objects, Java automatically provides a constructor But, if you create your own constructor, the automatically created constructor no longer exists As with other methods, you can overload constructors Overloading constructors provides a way to create objects with or without initial arguments, as neededOverloading constructors provides a way to create objects with or without initial arguments, as needed
36
36 Using the this Reference Classes can become large very quickly Each class can have many data fields and methodsEach class can have many data fields and methods If you instantiate many objects of a class, the computer memory requirements can become substantial It is not necessary to store a separate copy of each variable and method for each instantiation of a classIt is not necessary to store a separate copy of each variable and method for each instantiation of a class The compiler accesses the correct object’s data fields because you implicitly pass a this reference to class methods Static methods, or class methods, do not have a this reference because they have no object associated with them
37
37
38
38 Class Variables Class variables- Variables that are shared by every instantiation of a class Class variables (and methods) are also refered to as “static” variables (or methods) because of the access modifier used to define them
39
39 Working with Constants Constant variable: A variable or data field that should not be changed during the execution of a program To prevent alteration, use the keyword finalTo prevent alteration, use the keyword final Constant fields are written in all uppercase letters For example:For example: COMPANY_ID
40
40 Using Automatically Imported, Prewritten Constants and Methods The creators of Java created nearly 500 classes For example:For example: System, Character, Boolean, Byte, Short, Integer, Long, Float, and Double are classes These classes are stored in a package, or a library of classes, which is a folder that provides a convenient grouping for classes
41
41 java.lang – The package that is implicitly imported into every Java program and contains fundamental classes, or basic classes Fundamental classes include: System, Character, Boolean, Byte, Short, Integer, Long, Float, and DoubleSystem, Character, Boolean, Byte, Short, Integer, Long, Float, and Double Optional classes – Must be explicitly named Using Automatically Imported, Prewritten Constants and Methods
42
42 Using Prewritten Imported Methods To use any of the prewritten classes (other than java.lang): Use the entire path with the class nameUse the entire path with the class nameOR Import the classImport the classOR Import the package which contains the class you are usingImport the package which contains the class you are using
43
43 Using Prewritten Imported Methods To import an entire package of classes use the wildcard symbol * For example: import java.util.*;import java.util.*; Represents all the classes in a packageRepresents all the classes in a package
44
44 Access Specifiers http://www.uni-bonn.de/~manfear/javamodifiers.php
45
45 Key Concepts Learned Today Objects Classes Constructors Overloaded constructors Method declarations Scope specifiers
46
46 Next Week: Key topics Advanced OOP conceptsAdvanced OOP concepts InheritanceInheritance AggregationAggregation EncapsulationEncapsulation Read Chapter 9 Read Articles in eResource (Week 4 and 5) ArraysArrays ObjectsObjects Review WS4 Programming assignment Team project approval
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.