Class and Objects in Java

Class and Objects in Java

Java is an object-oriented programming language.For short it is called as OOP. So the programs made with java consists of classes and objects,so what is classes and objects

Classes

classes are just a template or blue print for objects (just a template code). This can have its own methods and variables. creating class doesn’t occupy space in memory

For example Student is a class ,this contains all details like name ,class, rollno, grade, gender

For this same Student class pupils John, Alex, Danny, Abella are the Objects ,these objects have properties like name, grade, class, rollno, gender

Class creation syntax

class ClassName {
// variables
// methods
}

Class Example

class student
{
String name;
int age;
void show()
{
System.out.println(name);
System.out.println(age);
}
}

in the above there are two class variables(instance variables) name and age of the student and a method named show( ) ,where print functions are executed when this method is called

Creating only classes is no use, and by creating classes no memory will be occupied by the program. Objects should be created to the classes ,and this objects occupy memory in the program

NOTE: Object cant be created if there is no class

Objects

An object is an instance of a class, the memory will be assigned when created. objects can be communicated without other object data. An object represents an entity in the real world that can be distinctly identified. you can create any number of objects

As dicussed above, For this same Student class pupils John, Alex, Danny, Abella are the Objects ,these objects have properties like name, grade, class, rollno, gender

Object creation syntax

className object = new className();

Object example

public class example{
public static void main(String args[])
{
student s=new student();
s.age=40;
s.name="codeskulls";
s.show();
}
}

className is the class name that we want to create a object for it,here student is class name

object is the object name, here s is the object name

new keyword is used to allocate memory

className( ) is the constructer, constructer is used to create a object ,we will discuss this in further topics, here constructor is student( )

. (dot) operator is used to access the variables(members) and the methods of their objects,in this example s.age=40 ,we are assigning age 40 to the age member for student s

Classes and Objects Example

class student
{
String name;
int age;
void show()
{
System.out.println(name);
System.out.println(age);
}
}
public class example{
public static void main(String args[])
{
student s=new student();
s.age=40;
s.name="codeskulls";
s.show();
}
}
Last updated on by vishal devxo