
Java fully supports object oriented programming. There are four pillars of object oriented development: encapsulation, data hiding, inheritance (code reuse), polymorphism.
What is a class?A class is a prescription for a particular kind of object. We can use the class definition to create objects of that class type, that is, to create objects that incorporate all the components specified as belonging to that class.
In essence, a class definition is very simple. There are just two kinds of elements that you can include in a class definition:
variables (attributes)- The elements that differentiate one object of the class from the other
methods (behaviour) - The operations you can perform for the class- these determine what you can do to, or with, objects of the class. Methods operate on the variables of the class.
Object orientation uses class to encapsulate (i.e. wrap together) variables and methods. Encapsulation allows the client of your class to use it without knowing or caring about how it works. You can recall, you used the ReadNum class without understanding how it worked. You only knew what it did. In real life situations, we use several things without understanding how they work. You can drive a car without understanding how the internal combustion engine operates. Similarly, the clients of your class can use them without knowing how your class does what it does. The actual inner working of the class should be hidden: user needs to know what it does and not how it does it.
For example, a DVD player encapsulates all the attributes and behaviours that enable you to watch a movie. The companies that make televisions do not make DVDs. But, you can connect them together to watch the movie. The components of the television are encapsulated inside the television. Encapsulation enables objects to hide their implementation from other objects by a principle called Data Hiding.
Variables in a
Class DefinitionAn object of a class is referred to as and instance of that class. There are two kinds of variables in a class definition:
Instance variables: These are associated with objects. Each instance of the class will have its own copy of each of these variables. These differentiate one object from another.
Class variables: These are associated with class. A given class will have only one copy of its class variable A class variable must be declared using the keyword static preceding the type name.
Methods in a Class
DefinitionThe methods that you define in a class provide the action that can be carried out using the variables specified in the class definition.
Analogous to the variables in class definition, there are two kinds of methods, instance methods and class methods. You can execute class methods even when no objects of a class exist, whereas instance methods can only be executed in relation to a particular object. Again, like class variables, class methods are declared using the keyword static.
Perhaps the most common use for class methods is when a class is just used to contain a bunch of methods, rather than as a specification for objects. All executable code in java has to be within a class, but there are lots of general utility functions that you need that don't necessarily have an object association. For example, the readInt() function from ReadNum class.
Defining ClassesTo define a class you use the keywords class followed by the name of the class, followed by a pair of braces enclosing the details of the definition.
public class Circle {
static final double PI =3.14; //class variable that has a fixed value
double radius; //Instance variable
//Instance method to calculate area
double area(){
return PI*radius*radius;
}
//Instance method to calculate the perimeter
double circumference(){
return 2*PI*radius;
}}//end of class
When you declare a variable of type Circle with the statement:
Circle disc; //declare a variable
all you have created at this point is the variable disc.
To initialize disc with an object, you could write:
disc = new Circle( );
Now we have a Circle object. The object is created in memory and will occupy sufficient memory to accommodate all the data necessary to define the object.
Of course, you can do the whole thing in one step, with the statement:
Circle disc = new Circle( );
To put what we know about classes to use, we can use our Circle in an example.
You will be creating two files. The first is the file CreateCircle.java which will contain the class definition with the method main( ), where execution of the program starts. The second is the file Circle.java which will contain the definition of the class Circle.
public class CreateCircle {
public static void main(String[] args) {
Circle disc = new Circle(); //Create a cirle
disc.radius=5;
//output the Area and Circumference of the circle
System.out.println("The area is " +disc.area()+"\nThe Circumference is "+disc.circumference());
}//end of main method
}//end of class
Controlling Access to MembersThe access modifiers public and private control access to a class's variables and methods. All the classes we have defined so far have had members that are freely accessible within the same project. This applies both to the methods and the variables that were defined in the classes
Broadly, unless you have good reasons for declaring them otherwise, the variables in a class should be private and the methods that will be called from outside the class should be public.
The setRadius method in the following class Circle can be used by other classes to set the radius of the circle.
public class Circle {
static final double PI =3.14; //class variable that has a fixed value
private double radius; //Instance variable
public void setRadius(double rad){
radius = rad;
}
//Instance method to calculate area
public double area(){
return PI*radius*radius;
}
//Instance method to calculate the perimeter
public double circumference(){
return 2*PI*radius;
}
}//end of class
ConstructorsWhen you create an object of a class, a special kind of method called a constructor is always invoked. If you don't define a constructor for a class, the compiler will supply a default constructor which does nothing. The primary purpose of the constructor is to provide you with the means of initializing the instance variables for the object being created.
A constructor has two special characteristics which differentiate it from methods:
|
|
A constructor never returns a value and you must not specify a return type- not even of type void |
|
|
A constructor always has the same name as the class |
We could add a constructor to our class Circle:
public class Circle {
static final double PI =3.14; //class variable that has a fixed value
private double radius; //Instance variable
//Constructor to set the radius as the object is created
public Circle(double rad){
radius = rad;
}
//Instance method to calculate area
public double area(){
return PI*radius*radius;
}
//Instance method to calculate the perimeter
public double circumference(){
return 2*PI*radius;
}
}//end of class
The Variable thisEvery instance method has a variable with the name this, which returns to the current object for which the method is being called.
When you write the code for a method, we've seen that there are four different sources of data available to you:
|
|
Arguments passed to the method which you refer to by using parameter names. |
|
|
Class data members, both instance variables and class variables which you refer to by their variable names. |
|
|
Local variables declared in the body of the method. |
|
|
Values that are returned by other methods that are called. |
You can use a name for a local variable in a method, or possibly a parameter, that is the same as the name of a class data member. In this case you must use the keyword this when you refer to the data members in the method.
void getRadius (double radius){
//Change the instance variable to the argument value
this.radius = radius;
}
Method OverloadingJava allows you to define several methods in a class with the same name, as long as each method has a set of parameters that is unique. This is called method overloading.
The name of a method together with the type and sequence of the parameters form the signature of the method, and the signature of each method in a class must be distinct to allow the complier to determine exactly which method you are calling, at any particular point.
Note that the return type has no effect on the signature of the method. You cannot differentiate between two methods just by the return type.
Multiple ConstructorsIn most situations, you will need to generate objects of a class from different sets of initial defining data. If we just consider our class Circle, we would conceive of a need to define a Circle object in a variety of ways. You might want a constructor that accepted the radius. Another possibility is that you may want to create a default Circle with the radius of 1.0, so no arguments would by specified at all. This requires two constructors.
public class Circle {
static final double PI =3.14; //class variable that has a fixed value
private double radius; //Instance variable
//Constructor1 to create default circle
public Circle(){
radius = 1.0;
}
//Constructor2 to accept the radius
public Circle(double rad){
radius = rad;
}
//Instance method to calculate area
public double area(){
return PI*radius*radius;
}
//Instance method to calculate the perimeter
public double circumference(){
return 2*PI*radius;
}
}//end of class
Now, take a look at the following class CreateCircle which uses the class Circle.
public class CreateCircle {
public static void main(String[] args) {
//C1 is created using the default constructor
//The radius is set to 1.0
Circle C1 = new Circle();
//C2 is created using the second constructor
//The radius of C2 can be set to any value we want
Circle C2 = new Circle(10);
System.out.println("The area of C1 is " + C1.area());
System.out.println("The area of C2 is " + C2.area());
}//end of main method
}//end of classs
when you run the above program, you will get the output as follows:
The area of C1 is 3.14
The area of C2 is 314.0
__________