Chapter 9. Methods


Chapter 9. Methods

In Chapter 8 we learned that a class can declare variables . A class can also declare methods. A method, in the simplest way of looking at it, is a named block of code that can be called from another part of a program. In non-object-oriented programming languages, such as C or Fortran, the method (or function or subroutine) is the basic building block of the program. Methods are used to divide the program into functional units. There are no access restrictions associated with a C or Fortran method. It can be called directly from anywhere in the program.

In Java, methods are an integral part of the object-oriented framework, but they are not the basic building block of a Java program ”the class serves that function. Java methods are members of a class. Among other things, methods are used to access, change, and manipulate the fields of a class. Java methods have an access associated with them that defines how and when the method can be accessed outside of its class. You can define instance methods that are associated with an instance of a class or static (class) methods that are associated with the class itself. You can also define a method to be abstract , final , synchronized , or native .

Methods play a key role in the object-oriented concepts of encapsulation, inheritance, and polymorphism. According to the idea of encapsulation, you should not give direct access to the fields declared in a class. These should be given private access and access to them provided through methods. A subclass inherits the nonprivate methods from its superclasses. The subclass can use the inherited methods as they are or it can overload or override the methods as it sees fit, to implement polymorphism.

The topics we will cover in this chapter are ”

  • Declaring methods

  • Naming conventions

  • Access modifiers

  • Instance methods

  • Static methods

  • The main() method

  • Input parameters

  • Abstract methods

  • Final methods

  • The native and synchronized keywords

  • Method chaining

  • Method overloading

  • Method overriding

  • The return statement



Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net