Class , Methods , Objects in Java ( Basic of Java )
- Mahesh Bhat M
- Jul 3, 2017
- 2 min read
Hai This post is for the beginners in Java . I explained simple way with example and in next post i am providing necessary example . Thank U
Object :−
Objects have states and behaviors.
Example: A dog has states - color, name, breed as well as behaviors – wagging the tail, barking, eating. An object is an instance of a class.
Class :−
A class can be defined as a template/blueprint that describes the behavior/state that the object of its type support.
Objects in JAVA :-
All these objects have a state and a behavior.
If we consider a dog, then its state is - name, breed, color, and the behavior is - barking, wagging the tail, running.
If you compare the software object with a real-world object, they have very similar characteristics.
Software objects also have a state and a behavior. A software object's state is stored in fields and behavior is shown via methods.
Classes in Java
A class is a blueprint from which individual objects are created.
Following is a sample of a class.
Example :
class rectangle /**rectangle is a class name */
{
int length ; int width ; /** declaration of the class variable */
void getdata ( int x, int y) /** declaration of the class method*/
{
length = x ;
width = y ;
}
}
A class can contain any of the following variable types.
Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.
Instance variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated.
Class variables − Class variables are variables declared within a class, outside any method, with the static keyword.
A class can have any number of methods to access the value of various kinds of methods.
Creating an Object :-
An object is created from a class. In Java, the new keyword 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.
Instantiation − The 'new' keyword 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 :--
Rectangle rect1; /** decalare the oblect */
rect1=new Rectangle(); /** Instantiation the objects */
/** NEW is a keyword which allocates the memory for the rect1 objects */
Comments