Java - Class - Introduction

Java

In this tutorial we will learn about Classes in Java programming language.

Java is an Object Oriented Programming OOP language and so the code we write are all in classes.

We have been using classes since the beginning of this tutorial series. Now lets talk about what classes are in detail.

So, open your favourite Java IDE and lets write some code.

What is a Class?

A Class in Java is a wrapper that wraps data and methods that acts on that data.

To create a class in Java we use the class keyword.

Class syntax

class ClassName {
  // some code...
}

Where, ClassName is the name of the class.

Naming classes

Remember the following points when naming classes.

  • Start the name of the class using capital letters.
  • Use a-z, A-Z, 0-9 and underscore _ to name a class.
  • Use simple and descriptive class names.
  • Don't start your class name using digits.
  • Avoid acronyms unless then are popular like CSS or HTML etc.
  • Avoid keywords like while, break etc.

Class name examples

Following are valid class names.

class HelloWorld {
}

class FindAverage {
}

class Super_User_Account {
}

Following are invalid class names.

// can't start with digit
class 123 {
}

// can't use space
class Hello World {
}

// use of special character like * is not allowed
class *Hello {
}

Example: PackagingBox Class

Lets say we are writing a Java program for a company that handles packaging of items in boxes.

So, for this we can create a Java class by the name lets say PackagingBox and our code will look like the following.

class PackagingBox {
  // some code...
}

In the next tutorial we will learn about member variables that will help us to store data.

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT