Friday, 18 August 2017

Class and Object


Java is an object-oriented programming (OOP) language.

In this post we will learn how you can create custom class and objects in your Java program.

What is Object ?

Object is real world entity which has state and behavior

These objects share two characteristics:
  • State
  • Behavior

Let’s see example
            
             Object : tennis court

      • State : color, surface
      • Behavior:doCourtBooking, doCourtCleaning
What is class:

Before you create objects in Java, you need to define a class.

Basically A class is a use define data type
            
A class is declared using class keyword. A class contain both data and code that operate on that data. The data or variables defined within a class are called instance variables and the code that operates on this data is known as methods. Thus, the instance variables and methods are known as class members.

Remember following things while creating class and object :
·       
       A class can have only public or default(no modifier) access specifier.
·        
       It can be either abstract, final or concrete (normal class).
·        
       It must have the class keyword, and class must be followed by a legal identifier.
·        
       It may optionally extend one parent class. By default, it will extend java.lang.Object.
·        
       The class's variables and methods are declared within a set of curly braces {}.
·        
        It is not necessary that the .java file name and class name must be same,you can name it differently. Because when we compille code the .java file compile and the .class name file will be created ,and when we run the programe class file will be run with .class file name.

A simple class example:

Code
class Student
{
    String name;
    int rollno;
    int age;
    void get(String name,int rollno,int age)
    {
                this.name = name;
                this.rollno = rollno;
                this.age = age;
    }
    void display()
    {
                System.out.println("Name is "+name);
                System.out.println("rollno is "+rollno);
                System.out.println("rollno is "+age);                  
    }
}
class school
{
   public static void main(String args[])
   {
                Student stu = new Student();
                stu.get("technews",80,21);
                stu.display();
   }
               
}

Output:
Name is technews
rollno is 80
rollno is 21

This Example create stu named object which has get() and display method and name rollno and age as a attribute.


In this post we learned about object and class in java.

0 comments:

Post a Comment