Java Class

 

Classes & Objects

A java class is the blueprint for an object. A java object is a software bundle of related state and behavior. The software object is often used to model the real world objects that we see everyday such as desks, pets, and so on. Before an object is created, the programmer determine the fields and methods that are necessary, and then creates a class. Hence, a class is a blueprint of the objects that may be created from, so a class is not an object but it can be a description of an object. Each object created from a class is called an instance of the class. We have two types of classes, a private and public class. A private class, the member cannot be accessed by code outside the class. The member can be accessed only by methods that are members of the same class. A public class, the member can be accessed by code inside the class or outside. Now lets see a basic example on how class and object works.

Example

First, we create a java class without the main method, then we create another class with the main method in it. The two java classes should be in the same directory.

Here is the first class:

 

Here is the second class which contains the main method:


 

ClickHere to download firstclass.java 

ClickHere to download secondclass.java 

The above program we created a class without the main, inside the class, it contains two methods. One method is to set the name and the other method will returns the name. Hence, in other class which contains the main method, we created a object " SetName sname = new SetName()". By creating the object, we can access the SetName class using the object name that we created which is "sname". To access the SetName class, simply we use the object name "sname" followed by a period and the methods we want to access. Now lets see a bit more complicated example.

Here is the first class:

 

Here is the second class:

 

ClickHere to download firstclass.java 

ClickHere to download secondclass.java 

More about Class

Often time we can have two or more methods in a class that consists the same name as long as their parameter lists are different. This also applies to constructors. We call this Overloading methods and constructors. Method overloading is an important part of object-oriented programming. When a method overloaded, it means that multiple methods in the same class have the same name, but different types of parameters. Method overloading is important because sometimes we need several different ways to perform the same operation.  Lets see an example on how it works. Recall, from our " Summary " chapter, we have an Atm program. For this example we will use the same Atm program.

Here is the first class:

 

Here is the second class:



ClickHere to download firstclass.java 

ClickHere to download secondclass.java 


 

 

  <Java 24><Home>