Java Class Basic Components – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Sat, 13 Aug 2022 16:47:40 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg Java Class Basic Components – Programmerbay https://programmerbay.com 32 32 Java Class Definition and its Basic Components with Program Example https://programmerbay.com/java-class-definition-and-its-basic-components-with-program-example/ https://programmerbay.com/java-class-definition-and-its-basic-components-with-program-example/#respond Sun, 14 Aug 2022 16:54:08 +0000 https://programmerbay.com/?p=5096 Java supports encapsulation which is one of the essential features of OOPs. Encapsulation can be defined as a way of binding attributes and behaviour together into a single unit. Class is one such example.

A class is a basic fundamental in Java. It encapsulates data and behaviour within a single unit. It is used to define a new data type and enables us to create an object of that type. Therefore, it is considered a template or blueprint or prototype.

A class consists data and the code which operates on it. It is declared using class keyword.
Below is the simple form of class definition:

class classname { 
type instanceVariable; 
type methodName(parameterList) { 
// body of method 
} 
}

Explanation :

  • The data or variable within a class is known as an instance variable. Each instance or object of a class owns a separate copy of that variable.
  • The behaviour or method operates on the data and performs a specific task.
  • Both variables and methods defined within the class are known as class members.

Further, a class doesn’t necessarily to have a main() method. The method is declared only to that class, which acts as the program’s starting point. However, Applet doesn’t need it.

How to Define a Class ?

A class represents a templates that specify the nature of real life entity. In other words, it resembles new data type and that class is used for creating instance of that type.

class Person {
    String name;
    int age;

    public static void main(String[] args) {

        Person reader = new Person();  // A reader is a person with different attributes
        Person writer = new Person();  // A writer is another person with has its own attributes

        // reader attributes, like what his name and age
        reader.name = "Josh";
        reader.age = 19;

        System.out.println("Reader name is "+ reader.name + " Age is "+reader.age);

        // writer attributes, like what his name and age
        writer.name = "Karen";
        writer.age = 26;

        System.out.println("Writer name is "+ writer.name + " Age is "+writer.age);
        
    }
}

Output: 

Reader name is Josh Age is 19 
Writer name is Karen Age is 26

Explanation:

In Java, each object has its copy of data. Therefore, if one creates two objects of the same class i.e “Person”, then each would have a separate copy of data. If any data in an object changes, it would not reflect others.


To explain this better. In the above code, we created two objects and assigned their properties with some values. Now, printing those objects would provide different values as they had their own copy of data.

 

Java Objects Definition

Everything in Java is viewed as a real-life entity i.e shape, or person, termed as an Object. A class defines its attributes and behaviour.


A class name is used to create an object, and its creation consists of two steps.
1) A variable of that class type is declared and used to hold the reference of an actual copy of the object
2) new operator is used for allocating memory in heap dynamically. It returns the address of the object

Syntax:

Person person; // declare reference to object 
person = new Person(); // allocate a person object

In short, a variable of a class type just carries reference of an actual object that is assigned to it.

Untitled Diagram.drawio 2

Like C++, a constructor is used to initialize an object at the time of its creation. If no constructor is provided explicitly, Java compiler automatically supplies default constructor.

What are the major components of Java class?

These are the major component of a class in Java :

  • Attributes or Variables
  • Behaviour or Methods
  • Constructor

Java Variables

A variable takes a certain space to store a value which can be changed during program execution.

How to define a variable in Java?

When a variable is declared, a memory location allocates to it based on the provided data type. These variables carries a default value, if not initialized. 

It can be declared with the below syntax :

private int variableName;

private : A access modifier that controls visibility scope of a field. 

int: A primitive data type that tells JVM what type of values a variable can hold and how much space needs to be allocated.

variableName: It is an unique identifier or unique name that is used throughout the program to access it.

How to initialize a variable in Java?

When a variable is assigned with a values, it is considered as the variable initialization. Below is the example :

public static void main(String[] args) { 
int x; 
x = 6; 
}

Variable declaration and initialization can be done at the same time.  Below is the example.

Java Variable Declaration

Java Method

A method is used to operate on data and perform a specific task. It increases code readability and reusability of a program. It changes the state of an object or entity by acting on attributes of that object.

Below is the syntax :

access_modifier return_type method_name(arguments){
// body
}

How to define a method?

A method definition consists of two parts :

1) Method deceleration: It involves attributes such as access specifier, non-access specifiers,methodName, returnType, and parameter lists.

2) Method body: The actual code where the logic to perform a task resides.

method java

Explanation:

public : A access modifier that controls the visibility scope of a field. In this case, it’s public which means, it’s accessible everywhere.

int: A return type which tells JVM what type of value is expected as output from a method. In this case, it’s int type

methodName: It is a unique identifier or unique name that would be used throughout the program to access it.

parameters: These are the values passed to a method. The values are provided by the calling method.

Below is the example :

public int sum(int x, int y){
 int total = x + y ;
 return total; 
}

How to call a method : 

To call a method, one needs to simply specify the method name followed by parenthesis with argument values (if it exists).

For example :

sum(2,3);

Java main() method definition and explanation

Java uses the main method as a starting point from where a program starts its execution. public static void main(String[] args) is an important method and is used by JVM (Java Virtual Machine) to identify the starting point of a program.


Without the main() method, the program can be compiled but can’t be executed.
It is important to have the main method in a class to execute a program.

PSVM Java

Explanation:

Access Modifier : It controls the accessibility or visibility scope of a class and its members. It can be package-level or class-level accessibility.


Static keyword: It is a non-access modifier. It can be used with class, methods or fields. When it is declared with a method, it is termed a static method. A static method doesn’t require an object or instance, instead, it can be invoked using classname. Therefore, the main() method is static and enables JVM to invoke it without actually creating an object of the respective class.


void: It is a return type. It specifies that the given method would return nothing. A program terminates after the main() method finishes its execution, and therefore, there is no point to return anything.


main(String[] args): ‘main’ is the method name which JVM looks for. It accepts a String array as input which is nothing but a command line argument list. Command line arguments are provided after the program name and this value is passed to your program at the time of program execution.

Java Constructor

A constructor is used to initialize an object. It’s is similar to a method, but a constructor is defined with the same name as class name and doesn’t have return type. If one doesn’t declare a constructor, JVM uses default constructor for initialization.

How to define a constructor?

A constructor syntax provided below :

    public className() {
// body

    }

JAVA program to demonstrate the working of Class

class ClassName{ 
int VariableName; 
void printMe() { 
System.out.println("variable = "+VariableName);
 }

 public static void main(String[] args) {    
        ClassName instance = new ClassName();         
        instance.VariableName =10;            
        instance.printMe();  
   }
 } 

Output:

classes

]]>
https://programmerbay.com/java-class-definition-and-its-basic-components-with-program-example/feed/ 0