Class and Object
In this chapter we will learn more details on a class and object.
A class can have fields, methods and classes.
Example --> public class MathOperations {
}
Variables can be declared using available datatypes.
Example --> public int i;
methods are declared using access Modifiers and data types.
we can write same methods name multiple times with different
number and types of parameters. This concept is called method
overloading.
Here is an example.
public class MathOperations {
public int calSUM(int a , int b) {
//statements
}
public int calSUM(int a, int b, int c) {
// statements
}
}
calSUM() method can be found two times in the class with different
number of parameters. first method allows two parameters as input and
second method allows three parameters as input. You can also add another
method with the same , with same number of paraters but with different
data types.
Object
To optimise the code, we do use the existing program and code segments inside
that. In java, we do this by creating an object and use the methods and fields
inside that. What is an object? object is a copy of class which get processed
indipendently of the main class. We can create many objects on the same class.
using "new" keyword we can create an object of class MathOPerations.
MathOperations myobj = new MathOperations();
MathOperations myobj2 = new MathOperations();
Now we can call the functions defined in MathOperations calls using object created.
myobj.calSUM(2,3);
myobj2.calSUM(4,5);
Here we have created two objects for the same class. myobj, myobj2.
These two objects are the copy versions of main class MathOpertions.
these two will run in two separate memory locations. we need to treat
them as separate programs of same class type.
When we want to use one class in another class (or) in the same class
we create an object on that class and use the methods and fields inside
that
Constructor
Constructor is a default method in every class. Even we dont define a contructor
method compiler does add deafult constructor to every class. It has the same name
as the classname and does not return any value. Generally it will be used to
initialize or set values to class variables. This method automatically will get called
when we create a new object.
class MathOpertions {
public int var1;
public int var2;
MathOperations() { System.out.println("First method"); }
MathOperations(int i, int j) {
var1 = i;
var2 = j;
System.out.println("Second method");
}
public static void main(String[] args) {
MathOperations obj1 = new MathOperations();
MathOperations obj2 = new MathOperations(1,2);
}
}
Output
------
first method
Second method
When obj1 get created using new keyword, first method will called.
When obj2 get created using new keyword, second constructor will get called.
|