Methods, classes, and Objects - PowerPoint PPT Presentation

About This Presentation
Title:

Methods, classes, and Objects

Description:

Methods, classes, and Objects Dr. Jim Burns More on Instance Methods However, if you are creating a class from which objects will be instantiated, most methods will ... – PowerPoint PPT presentation

Number of Views:64
Avg rating:3.0/5.0
Slides: 50
Provided by: burnsBaT
Learn more at: http://burns.ba.ttu.edu
Category:

less

Transcript and Presenter's Notes

Title: Methods, classes, and Objects


1
Methods, classes, and Objects
  • Dr. Jim Burns

2
Question
  • Which of the following access modifiers is the
    default modifier?
  • public
  • private
  • protected
  • package

3
Question 2
  • Which of the following access modifiers is needed
    to enable a class to be used without being
    instantiated?
  • Public, private, static, void, protected

4
Question 3
  • Methods are invoked using parameters
  • System.out.printlin(With raise, salary is
    newamount)
  • Method headers have arguments
  • Println(string args)
  • Do the parameters and arguments occupy the same
    locations in memory?

5
Question 4
  • In the statement
  • System.out.printlin(With raise, salary is
    newamount)
  • Println() is the method name?
  • What is System?
  • What is out?

6
Using Methods, classes, and Objects
  • Methods are similar to procedures, functions, or
    subroutines
  • Statements within a method execute only when the
    method is called
  • To execute a method, you call it from another
    method
  • The calling method makes a method call
  • Execution starts with the main method

7
Simple methods.
  • Dont require any data items (arguments or
    parameters), nor do they return any data items
    back
  • You can create any method once and use it many
    times in different contexts

8
Example
  • Public class First
  • Public static void main(String args)
  • System.out.println(First Java application)

9
Method Declaration
  • Is the first line or header of a method and
    contains
  • Optional access modifiers
  • The return type for the method
  • The method name
  • An opening parenthesis
  • An optional list of method arguments separated by
    commas
  • A closing parenthesis

10
Access Modifiers
  • public accessible anywhere
  • private accessible only within the class in
    which it is defined
  • protected accessible only to derived
    (inherited) classes only
  • package is the default
  • static does not require instantiation before it
    can be used and remains in place after use,
    without being destroyed

11
Implementation hiding
  • The encapsulation of method details within a
    class
  • You dont know the algorithm being used inside
    the method
  • prinAndInter intrRate prin prin
  • prinAndIntr (1intrRate) prin

12
Implementation hiding
  • We use televisions, telephones, computers,
    automobiles without understanding much about
    their internal mechanisms

13
Method declaration
  • modifiers name(arg_type arg1, arg_type arg2,
    arg_type arg3)
  • HOWEVER,
  • modifiers name(arg_type arg1, arg2, arg 3)
  • IS INCORRECT!!
  • Each arg must be preceded by its own data type

14
Argument types
  • Can be any of the primitive types
  • Can be any of the predefined class types
  • Assume a class customer exists
  • Public void approveCredit(customer oneCustomer)

15
Consider the following
  • Public static void predictRaise(double
    moneyAmount)
  • Double newAmount
  • newAmount moneyAmount 1.1
  • System.out.println(With raise, salary is
    newAmount)

16
Now consider this
  • Public static void predictRaise(double
    moneyAmount)
  • Double newAmount
  • newAmount moneyAmount 1.1
  • System.out.println(With raise, salary is
    newAmount)
  • moneyAmount 10000

17
Would this change ..
  • The value of salary in
  • predictRaise(salary)
  • ???

18
No
  • Because Java supports passing of values rather
    than passing addresses, so
  • The values of the parameters in the calling
    statement are copied into the arguments of the
    header.
  • The parameters and their associated arguments
    occupy different locations in memory
  • C supports both pass-by-address and
    pass-by-value

19
Further, at the end of
  • the usage of predictRaise(salary) the storage
    used by the instantiation of the method is
    released back, unless the method is declared
    static, so the assignment of 10000 to moneyAmount
    is lost

20
  • public class DemoRaise
  • public static void main(String args)
  • double mySalary 200.00
  • double moneyAmount 800.00
  • System.out.println("Demonstrating some
    raises")
  • predictRaise(400.00)
  • predictRaise(mySalary)
  • predictRaise(moneyAmount)
  • public static void predictRaise(double
    moneyAmount)
  • double newAmount
  • newAmount moneyAmount 1.10
  • System.out.println("With raise, salary
    is " newAmount)

21
Creating Methods that Require Multiple Arguments
  • Public static void predictRaiseUsingRate(double
    money, double rate)
  • double newAmount
  • newAmount money (1 rate)
  • System.out.println(With raise, new salary is
    newAmount)

22
In the above
  • The order in which the paramters are passed must
    be consistent with the order in which the
    arguments are declared in the header
  • money
  • rate

23
Creating Methods that Return Values
  • Public static double predictRaise(double
    moneyAmount)
  • double newAmount
  • newAmount moneyAmount 1.1
  • Return newAmount
  • Whats different???

24
This method would be invoked using
  • Double mySalary
  • Double myNewSalary
  • mySalary 1000
  • myNewSalary predictRaise(mySalary)

25
Could also do something like
  • System.out.println(New salary is
    calculateRaise(mySalary))
  • OR
  • SpendingMoney calculateRaise(mySalary)
    expenses

26
Learning about Class Concepts
  • When thinking in objects, everything is an
    object, and every object is a member of a class
  • Your desk is a member of the class that includes
    all desks and your car is a member of the class
    that includes all cars
  • These are called is-a-relationshipsrelationships
    in which the object is a member of the class

27
An object
  • Is an instantiation of a class (one tangible
    example of a class)
  • A Buick, a Toyota Camry, and a Volkswagon Jetta
    are all instantiations of the class automobile

28
Creating a Class
  • Begins with a header declaration
  • Continues with the body
  • Data fields (instance variables)
  • Methods
  • Fields are named variables that you declare
    within a class, but outside of any method
  • Data fields are also called instance variables

29
Class header declaration (one or more)
  • An optional access modifier
  • The keyword class
  • Any legal identifier you choose for the name of
    your class
  • Public class employee

30
Fields (also called data fields)
  • Are instance variables
  • Are accessible to all methods within the class
  • Are usually declared private
  • If private, they can only be accessed (read or
    changed) by methods within the class
  • This is called information hiding

31
Information Hiding
  • Class fields are declared private
  • Class methods are declared public
  • The only way another class can access a classs
    fields is by use of one of its public methods

32
Creating Instance Methods in a Class
  • Public class employee
  • private int empNum
  • public int getEmpNum()
  • return empNum
  • This is an instance method that assumes empNum
    has been defined

33
Instance Methods
  • Unlike class methods, instance methods do not
    employ the static modifier.
  • Static is used for class-wide methods, but not
    for methods that belong to objects
  • When you are creating a main method within a
    class, many of the methods invoked by the main
    will be declared static so they can be invoked
    without calling them from within the main

34
More on Instance Methods
  • However, if you are creating a class from which
    objects will be instantiated, most methods will
    probably be non-static because you will associate
    the methods with individual objects

35
Declaring Objects and Using their Methods
  • Declaring a class does not create any objects
  • A class is just an abstract description of an
    object
  • Suppose a class Employee has been defined
  • Employee someEmployee
  • Creates an instance of Employee

36
Notice in the above
  • That class names will begin with a cap
  • Variables and instances of classes (objects) do
    not
  • Just as a convention

37
Declarations
  • int someValue
  • Complier sets aside space for someValue (4 bytes)
    at compile time
  • Employee someEmployee
  • Again, compiler is notified that you will use the
    identifier someEmployee as an instance of the
    class Employee

38
Instantiations can be done as follows.
  • Employee someEmployee
  • someEmployee new Employee()
  • Here you informed the compiler that the
    identifier someEmployee will be an instance of
    Employee and second, you told the compiler to set
    aside enough space for the object (instance)
    someEmployee at run time

39
This is dynamic storage allocation
  • The actual object someEmployee does not exist
    until the new operator is encountered
  • You can use
  • Employee someEmployee new Employee()
  • Here you are declaring and establishing code to
    create a new instance of the class Employee at
    the same time

40
Organizing Classes
  • Public class employee
  • private int empNum
  • private String empLastName
  • private String empFirstName
  • private double empSalary
  • // Methods will go next

41
The following is also equally acceptable
  • Public class employee
  • private int empNum
  • private String empLastName,
    empFirstName
  • private double empSalary
  • // Methods will go next

42
Order..
  • You can place the data and methods in any order
    or mix them up

43
Class Employee
  • public void setEmpLastName(String name)
  • empLastName name
  • public String getEmpFirstName()
  • return empFirstName
  • public void setEmpFirstName(String name)
  • empFirstName name
  • public double getEmpSalary()
  • return empSalary
  • public void setEmpSalary(double sal)
  • empSalary sal
  • public class Employee
  • private int empNum
  • private String empLastName
  • private String empFirstName
  • private double empSalary
  • public int getEmpNum()
  • return empNum
  • public void setEmpNum(int emp)
  • empNum emp
  • public String getEmpLastName()
  • return empLastName

44
An introduction to using Constructors
  • Employee chauffeur new employee()
  • Here you are calling a method named Employee()
    that is provided by default by the Java compiler
  • It is a constructor that is provided by the
    compiler

45
Employee chauffeur new employee()Can also be
written
  • Employee chauffeur
  • Chauffer new employee()
  • The first statement declares an object named
    chauffeur
  • The second statement instantiates the object
    named chauffeur
  • Memory is allocated when the second statement is
    encountered

46
Default constructors
  • Are provided by the compiler when the user does
    not provide one
  • They require no arguments

47
When using the default constructor, it will
specify the following values for data fields
  • Numeric fields are set to 0
  • Character fields are set to Unicode \u0000
  • Boolean fields are set to false
  • Fields that are nonprimitive objects themselves
    are set to null (or empty)

48
If you dont like these default values, or if you
want to perform additional tasks when you create
an instance of a class,
  • Then you must write your own constructor
  • Any constructor you write must have the same name
    as the class it constructs and constructor
    methods cannot have a return type

49
  • public class ComputeCommission
  • public static void main(String args)
  • char vType 'S'
  • int value 23000
  • double commRate 0.08
  • computeCommission(value, commRate,
    vType)
  • computeCommission(40000, 0.10, 'L')
  • public static void computeCommission(int
    value,
  • double rate, char vehicle)
  • double commission
  • commission value rate
  • System.out.println("\nThe " vehicle
  • " type vehicle is worth " value)
  • System.out.println("With " (rate
    100)
  • " commission rate, the commission
    is "
Write a Comment
User Comments (0)
About PowerShow.com