Class and Objects

What is Class?
A class is a group of objects that has common properties. It is a template or blueprint from which objects are created.

A class in java can contain:
  1. data member
  2. method
  3. constructor
  4. block
  5. interface
When we create a class in java, the first step is to define keyword class and then name of the class.
Next is class body which starts with curly braces {} which enclose property and methods of the class.

Template of class:
class <class_name>{  
    data member;  
    method;  
}  

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public class Dog {

 String breed;
 int ageC;
 String color;

 void barking() {
  // ..
 }

 void hungry() {
  // ..
 }

 void sleeping() {
  // ..
 }
}

Objects
In real-world, we see many objects around us like cars, dogs, cats etc. All these objects have a state and a behavior.

Example: A dog has states-color, name, breed as well as behaviors - wagging, barking, eating. 

An object is an instance of a class.

If you compare the software object with a real-world object, they have very similar characteristics.

A class provides the blueprints for objects. So basically an object is created from a class. In Java the new keyword is used to create new objects.

Syntax to create new object:
Dog D1 = new Dog();

1
2
3
4
5
6
public class Dog{

public static void main(String[]args){
         Dog D1 = new Dog();
     }
}

Example:

What is Java Class and Objects?




<-- Previous || Next -->

1 comment: