Java Object and Classes

Objects in Java:

An object is an instance of a class.

Software objects also have a state and behavior just like real world object.

A software object’s state is stored in fields and behavior is shown via methods.

Real world object example can be dog and it’s state can be name,breed,color and the behavior can be barking,wagging,running etc.

So in software development, methods operate on the internal state of an object and the object to object communication can be done via method that means internal connection in oop language like java is done by methods.

Classes in Java:
A class is a blue print/template from which individual objects are created.

Method:

A method is basically a behavior. A class can contain many methods.In method where the logic is written,data is manipulated and all the actions are executed here.

A sample of a class is given below:

A class can contain any type of the following Java variables:

Local Variables:

Variables defined inside methods,constructors or blocks of code are called local variables.

Instance Variables(Non-Static Variables):
It is outside method but inside class.It can be accessed form inside any method,constructors or blocks of that particular class.

Class Variables(Static Variables):
Class variables are declared with in a class, outside a method, with the static keyword.

Constructors in Java:

The main rule of constructors is that they should have the same name as the class.A class can have more than one constructor.

Example of a constructor is given below:

 

Creating an Object:

A class provides the blueprints for objects. SO basically an object is created from class. In java, the new key word is used to create new objects.

There are three steps when creating an object from a class:

Declaration: A variable declaration with a variable name with an object type.

Instantiate: The ‘new’ key word is used to create the object.

Initialization: The ‘new’ keyword is followed by a call to a constructor.This call initializes the new object.

Example of creating an object is given below:

Output:

Accessing instance variables and methods:

Instance variables and methods are accessed via created objects.To access an instance variable the fully qualified path should be as follows:

Example:

This example explains how to access instance variable and methods of class:

 

example:
d

Source file declaration rules:

package

import

class {}

Java Package:

In simple it is a way f categorizing the classes and interfaces.When developing applications in Java,hundreds of classes and interfaces will be written,therefore categorizing these classes is a must as well as makes life much easier.

Import statement:

import java.io.*

Example:

Employee.java

EmployeeTest.java

To get output we have to use public main function and call it in EmployeeTest.java
so the outputs is: