/* related posts with thumb nails */

Class & defining a class, creating objects and accessing class members:

Class is a collection of members, where members can be member variables (properties) and member functions (methods). A class in Java can be written using the keyword “class” A class with related properties and operations is also known as abstract data type.

Structure of a class:

import package-name;

class class_name [extends super_class] [implements interface_name]



Member functions;


The members of a class can be public or private. In java, we cannot have global variables or stand-alone functions. If a variable or a function has to be written, it must be a member of some or the other class. This is the reason why Java is known as true object oriented programming language.

Declaring data-members: It is similar to declaring local variables but they may have access modifies like public, private, static and etc.

Declaring methods: The syntax for declaring methods is shown below.

type method_name (parameter_list)




Method declaration has four parts:

The name of the method (methodname)

The type of the value the method returns (type)

A list of parameters (parameter-list)

The body of the method (definition)

The type specifies the type of value the method would return. This could be a simple data type as int as well as any class type. It could even be void type, if the method does not return any value. The name of the method is a valid identifier. The parameter list is always enclosed in parentheses. This contains variable names and types of those. Variables m the list are separated by commas. We write empty parentheses if there are no parameters.

Creating Objects: To create the instances of a class, we use the keyword new. The following shows the syntax to create the objects.

class-name object-name = new class-name();

for example: Student s1=new Student() creates an object by name ‘s1’ that belongs to the class ‘student’

Accessing Members of a class: The syntax to access the members of a class is shown below. But, this accessibility is controlled using the keywords public and private. If the members are private they cannot be accessed outside the class.

objectname.variablename = value;


Related Topics:


Post a Comment