Table of Contents

Java Defining Class

Let's consider a scenario Car as a class (template). It has properties such as a model, color, and year. It has methods such us gear(),stop() and brake(). Objects represent the class. Hence car1, car2, and car3 are the objects of class Car.

A class is a group of objects which have common properties. It is a user-defined data type with a template that serves to define its properties. To create a class, use the keyword class.

A class can contain any of the following variable types.

  • Local variables − Variables defined inside methods, or blocks are called local variables. Methods are used to perform certain actions, and they are also known as functions.

int area()
   {
       int length = 10; //local variable
       int breadth = 5; //local variable
       int rectarea = length*breadth; //local variable
       return rectarea;
   }

  • Instance variables − Instance variables are variables within a class but outside any method.

class Student
{
int rollno;// rollno is an Instance variable
void details(){
}
}

  • Class variables − Class variables are variables declared within a class, outside any method, with the static keyword. Keywords are reserved words.

class Student
{
static int rollno;// rollno is class variable
void details(){
}
}

Defining a Class:

Class consists of field declarations and method declarations.

Syntax:

class classname {
   field declaration;
   method declaration;
}

Example:

class Student { // Student is the classname

 // state or field declaration
 String name = "Anu";
 int mark1 = 50;
 int mark2 = 70;
 int mark3 = 60;

 // behavior or method declaration
  void total() {
   System.out.println("Total");
 }
  void average() {
    System.out.println("Average");
}}

The variables and methods of the class are embraced by the curly brackets that begin and end the class definition block.

i) Fields Declaration:

A Java field is a variable. This means that it represents a value, such as a numerical value or a text.

syntax:

class classname{
  type fieldname;
}

Example:

class Student{  
  String name ="Anu"  
  int mark1 = 50;
  int mark2 = 70;
  int mark3 = 60;
}
/* name, mark1, mark2 and mark3 are the fields declared inside the class Student

ii) Method Declaration:

A Java method is a function. It's a block of code that carries out an operation. Like Java fields, Java methods must be declared inside classes. A Java method can accept values from fields and return results back to other parts of the program.

syntax:

type methodname( parameter-list ){
   method-body;
}

Example:

void total() {
   System.out.println("Total");
 }
void average() {
    System.out.println("Average");
 }
/*total() and average() are the methods

Ask queries
Contact Us on Whatsapp
Hi, How Can We Help You?