Lesson 4: Class Methods and Constructors

Yakov Fain · 2015

Methods contain code for actions or functions a class can perform. This chapter discusses how to work with the methods in detail. Each class method performs some functionality, such as calculating tax, placing an order, or starting the car. The chapter also deals with a special type of method called a constructor. When a program creates an instance of a class, Java invokes the class's constructor, a special method that is called only once when the instance is being built with the operator new. A class has several overloaded constructors with different numbers of arguments. As with method overloading, the overloaded constructors give more choices in instantiation objects and helps avoid code duplication. The chapter creates a version of the Tax class with a three-argument constructor and adds a utility function to convert the tax value from dollars to euros, assuming the dollar-to-euro conversion rate is 1.25.

Read the paper · More papers on PaperTik