A class is a non-primitive or user-defined data type in Java, while an object is an instance of a class. A class is a basis upon which the entire Java is built because class defines the nature of an object.
Since all the activities in a Java program occur within a class, we have already been using classes and objects since the start of this Java tutorial. Of course, those were extremely simple classes that we have used, but we didn’t take advantage of the majority of the useful features of classes. There are many things that you do not know about Java classes and objects, so let us understand them in this tutorial.
Objects and Classes in Java
Let’s first understand the concept of Object and Class in Java –
Object:
An object is an identifiable entity with some characteristics, state and behavior. Understanding the concept of objects is much easier when we consider real-life examples around us because an object is simply a real-world entity. You will find yourself surrounded by the number of objects which have certain characteristics and behaviors.
For example, we can say ‘Orange’ is an object. Its characteristics are: spherical in shape and color is orange. Its behavior is: juicy and tastes sweet-sour.
Class:
A class is a group of objects that share common properties and behavior.
For example, we can consider a car as a class that has characteristics like steering wheels, seats, brakes, etc. And its behavior is mobility. But we can say Honda City having a reg.number 4654 is an ‘object’ that belongs to the class ‘car’.
It was a brief description of objects and classes. Now we will understand the Java class in detail.
Java Class
The core element of Object orientation in Java is the class. A class is often defined as the blueprint or template for an object. We can create multiple objects from a class. It is a logical entity that does not occupy any space/memory. Memory is allocated when we create the objects of a class type. A class contains properties and methods to define the state and behavior of its object. It defines the data and the methods that act upon that data.
Have you ever thought why a class is the blueprint of an object?? The reason is :
A class allows the programmer to define all the properties and methods that internally define the state and behavior of an object, and all the APIs that externally define an object, and also the complete syntax for handling encapsulation, abstraction, polymorphism, and inheritance. Therefore, we can say that a class is the BLUEPRINT of an object.
A class defines the shared characteristics like –
◉ The set of attributes/properties
◉ The set of behavior or methods or actions
◉ How to construct an object
Objects are the “instances” of a Class:
The class as a blueprint specifies what an object will look like. You can think of a class as a cookie cutter and an instance as an actual cookie!! Similarly, you can consider a class as “Mobiles” and Samsung, Nokia mobiles as objects of the class Mobile.
“Class is the basis of all Computation in Java”
A class forms the basis of all computation in Java. Anything that exists as a part of the Java program has to be present as a part of a class, whether it is a variable or a method or any other code fragments. The reason is that Java is a pure Object Oriented language, in which all the functionalities revolve around the classes and objects. All Java programs contain objects that interact with each other by calling methods.
Some Important points about a class:
◉ In Java, we can not declare a top-level class as private. Java allows only public and default access specifiers for top-level classes. We can declare inner classes as private.
◉ We can include any type of the three variables in Java – local, instance and static variables.
◉ There can be only one public class in a single program and its name should be the same as the name of the Java file. There can be more than one non-public classes in a single Java file.
◉ A public class is visible to all classes from all the packages.
◉ A class with default access is visible only to the classes within the same package.
◉ We can also use the non-access modifiers for the class such as final, abstract and strictfp.
◉ We cannot create an object or instance of an abstract class.
◉ No subclasses or child class can be created from a class that is declared as final.
◉ A class cannot be declared both as final and abstract at the same time.
Declaration of Java Classes
In order to bring class into existence, we should declare it. We can declare a class with the use of a class keyword.
The components of the Java Class declaration are –
1. Access Modifiers – We can access Java classes using any access modifiers such as public, private, protected and default.
2. Class Name – In Java, the class name generally represents nouns which should begin with a capital letter without any spaces.
3. Superclass (if any) – The name of the parent class is a superclass and its child class is a subclass, and child class inherits the properties of a parent using the extends keyword. A subclass can only inherit a single parent.
4. Interfaces (if any) – To declare an interface, we just write the keyword interface followed by the interface name.
5. Class Body – The class body follows the class declaration and embeds within curly braces {}.
The syntax for declaring classes:
<access-modifier> class <ClassName>
{
//Class body containing variables and methods
}
Example:
public class Student
{
String name;
int age;
void display()
{
//method body;
}
}
Code Snippet:
//declaring a class
public class Person
{ //class body starts here
//creating the data members of the class
static String name = "John";
static int age = 25;
//creating the methods of the class
void eat()
{
//methodBody
}
void study()
{
//methodBody
}
void play()
{
//methodBody
}
public static void main(String args[])
{
System.out.println("Name of the person: " +name);
System.out.println("Age of the person: " +age);
}
} class body ends here
Output:
Name of the person: John
Age of the person: 25
Creating Objects from a Java Class
We know that an object is an instance of a class. To create an object of a class, first, we need to declare it and then instantiate it with the help of a “new” keyword.
Syntax of creating an object of a class:
To create an object of a class, specify the class name, followed by the object name, by using the new keyword –
ClassName objectName = new ClassName();
Example:
MyClass object1 = new MyClass();
Accessing the members of a Java Class
We can access the data members of a class using the object of the class. We just write the name of the object which is followed by a dot operator then we write the name of the data member (either variables or methods) which we want to access.
Syntax of accessing data members and methods of a Java Class:
objectName.variableName; //accessing the variables
objectName.MethodName(); //accessing the methods
Example:
Object1.number; //accessing the variables
object1.display(); //accessing the methods
Code snippet to understand the usage of Java Class and Object:
//creating a class named City
public class City
{
//declaring class variables
public String name;
public long population;
//defining the method of the class
public void display()
{
System.out.println("City name: " +name);
System.out.println("Population: " +population);
}
public static void main(String args[])
{
//declaring the objects of the class City
City metro1,metro2;
//Instantiating the objects of the class using the new keyword
metro1 = new City();
metro2 = new City();
metro1.name ="Delhi";
metro1.population = 10000000;
System.out.println("Details of metro city 1:");
metro1.display(); //display() method is being invoked for the object metro1
metro2.name ="Bangalore";
metro2.population = 5000000;
System.out.println("Details of metro city 2:");
metro2.display(); //display() method is being invoked for the object metro2
}
}
Output:
Details of metro city 1:
City name: Delhi
Population: 10000000
Details of metro city 2:
City name: Bangalore
Population: 5000000
Using Multiple Java Classes
Using multiple classes means that we can create an object of a class and use it in another class. Also, we can access this object in multiple classes. One class contains all the properties, fields and methods while the other class contains a main() method in which we write the code which has to be executed. We often use this concept for proper organization and management of classes.
We have to keep one thing in mind that the name of the class should be the same as the name of the java file. Now, we will understand this with the help of an example, in which we will create two files in the same folder: ClassOne.java and ClassTwo.java
ClassOne.java :
public class ClassOne
{
String sentence = “Hello World”;
}
ClassTwo.java :
public class ClassTwo
{
public static void main(String[] args)
{
ClassOne object1 = new ClassOne();
System.out.println(object1.sentence);
}
}
Output:
Hello World
0 comments:
Post a Comment