Classes in Java

By YuwebDesign

A Class is an object constructor, a template/blueprint/definition/factory
for creating as many objects (or instances) as needed.

A class describes what an object knows and what an object does.

You can better visualize it as a human DNA – a definition of how something should be created when a program is running.

  1. Name of a class should be a noun
  2. starting with Capital letter: e.g., Car{}
  3. name of the java file should match the class name.

The contents of a class are called class members,
and these members can be methods or properties.

  1. Fields
  2. Methods
  3. Constructors
  4. Blocks
  5. Nested class and interface

Properties (variables, fields) store some value.

A Java field is a variable inside a class.
E.g, in a class representing an employee, the Employee class might contain the following fields:

  • name
  • position
  • salary
  • hiredDate

The corresponding Java class could be defined like this:

public class Employee {
  String  name     ;
  String  position ;
  int     salary   ;
  Date    hiredDate;
Declaring Class Fields in Java


[access_modifier] [static] [final] Type name [= initial value] ;
//only type and name are required.

Methods usually do something.

A method is like a function that is used to expose the behavior of an object.

Advantage of Method
  1. Code Reusability
  2. Code Optimization

Leave a Reply or Comment

Your email address will not be published. Required fields are marked *