Java Classes and Objects With Examples

Java Classes and Objects With Examples


Class

Class is an user denied data type that combine member data, and member method. Class is the fundamental block of oops. Class supports inheritance that increases the reusability of code.

Class keyword is used to declare a class.

Note -

  • Class is a keyword that is used to create class / tells the compiler that a new data type is created.
  • java.lang package contains a class whose name is class that is used to register the driver.
  • java.lang package contains a class whose name is object. Object class is used when type is unknown.

There’s one Class object for each class that is part of your program. That is, each time you write and compile a new class, a single Class object is also created (and stored, appropriately enough, in an identically named .class file). To make an object of that class, the Java Virtual Machine (JVM) that’s executing your program uses a subsystem called a class loader.

Object ob;
ob =
10;
ob =
"Ram";

Syntax - 

Class className{
   dataType variable;
  
// .....
   method Declaration;
}

 

We will understand Class better after studying Objects -

Object

  • Object ate runtime entity or instance of a class.
  • We can access class members from outside the boundary of a class with the help of object.
  • Every object contain separate copy of data members.

In simple words we can say that an object is one that has a distinct set of characteristics, and functionalities.

When you create a reference, you want to connect it with a new object. You do so, in general, with the new operator.

Syntax to create object -

 

ClassName objectName = new ClassName();

OR -

className objectName;
       objectName =
new className();

Data Members

All variable that are declared inside the boundary of a class, but outside all of the method bodies known as data members of a class.

We can also create multiple objects of a same class we will see with an example -

Example - Creating Multiple object of a same class.

In the above example, we saw not just the creation of multiple objects, but multiple classes as well.

Note -

  • When you create a reference, you want to connect it with a new object. You do so, in general, with  the new operator.
  • The keyword new says, “Make me a new one of these objects.”
  • You can say: String s = new String("asdf"); Not only does this mean “Make me a new String,” but it also gives information about how to make the String by supplying an initial character string. Of course, Java comes with a plethora of ready-made types in addition to String. What’s more important is that you can create your own types. In fact, creating new types is the fundamental activity in Java programming.