Class in Java
- A class in java is declared using class keyword.
- A class is a group of objects that has common properties. It is a template or blueprint from which objects are created.
- 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 in java.
- Class is a user described blueprint or prototype from which objects are created.
- It represents the set of properties or methods which might be common to all objects.
Class declaration include below additives, in order:
- Modifiers : a class may be public or has default access.
- class name : The name should begin with a initial letter.
- body: The class in java body surrounded via braces { }.
Syntax of class:
1 2 3 4 5 6 7 8 | // class Declaration class class_name{ data member; method; } |
Example: Simple Class Program [Area of Rectangle]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | // create an class Student class Student { // field or data member or instance variable int id; String name; public static void main(String args[]) { // creating an object of Student Student s1 = new Student(); // accessing member through reference variable System.out.println(s1.id); System.out.println(s1.name); } } |
Object in Java
- In real–world, we see many objects round us like automobiles, dogs, cats and so on. these kinds of objects have a state and a behavior.
- An object is an instance of a class.
- If you compare the software object with a real-world object in java , 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 object in java.
- It’s miles a basic unit of object orientated Programming and represents the real existence entities.
- An average Java program creates many objects, which as you already know, have interaction by way of invoking strategies.
An object includes :
- state : it’s represented by attributes of an object. It additionally reflects the properties of an object.
- behavior : it’s represented by means of methods of an object in java. It also reflects the reaction of an object with other objects.
- identity : It gives a completely unique name to an object and allows one object to have interaction with different items.
Syntax to create new object:
1 2 | // Create object of Dog class Dog D1 = new Dog(); |
Example:
1 2 3 4 5 6 7 8 9 10 | public class Dog { public static void main(String[] args) { // Object Creation method Dog D1 = new Dog(); } } |