Declarations and Program Structure

Hi all, and welcome back to JavaMadeEasy! Today I am going to talk about method declarations for data members, methods and constructors as well as the program structure for a main program that accesses two different classes.

Data members

SO lets go ahead and jump in to data member declarations. A data member is a variable of an object e.g. a bike owner object can have a name and price variable. There are three components in declaring a data member; access modifiers, data type and the name of the variable. See an example below.

private string ownerName;

Lets move on to method declaration. The purpose of a method is to perform a task by executing java code. The components used in defining a method in java are access modifier, return type, method name and parameter, in this order. In the method between the curly braces you can included the desired statements.

public void setOwner (String name ) {
ownerName =name ;
}

Constructor Declaration

A constructor is a special method that is executed when a new instance of the class is created. The purpose of a constructor is to initialize the object of a class.

Differences Between Constructors and Methods

I guess its a good time time to discuss some of the main differences between constructors and methods. Take a look at the following table that compares both.

ConstructorMethod
Initializes the object of a classPerforms a task by executing Java code
Have no return typeHave a return code
Cannot be abstractCan be abstract
Cannot be finalCan be final
Cannot synchronizeCan synchronize

end

Leave a comment

Design a site like this with WordPress.com
Get started