a) A static member of a class can be accessed using the class name, followed by a period, followed by the member name. With a class method, you also need to supply the parentheses enclosing any arguments to the method after the method name. The period here is called the dot operator. So if you want to calculate the square root of PI you could access the class method sqrt() and class variable PI that is defined in the Math class as follows: double a = Math.sqrt (Math.PI);
b) Instance variables and method can only be called using an object reference, as by definition they relate to a particular object. The syntax is exactly the same as we have outlined for static members.
Overloading of Methods
As already discussed earlier overloading is the important concept in OOPs which allows the feature of polymorphism in java. Overloading of methods means having the same method name, but different type and order or parameters and depending on the values passed, the program would know to call which method.
Code class Test31 {
public static void main(String[] args) {
Test31 x = new Test31();
x.met1(10);
x.met1("Hello",20);
}
void met1(int a) {
System.out.println("Method with one parameter");
}
void met1(String s, int a) {
System.out.println("Method with two parameters");
} }
Output
Method with one parameter Method with two parameters
So here we can conclude that the program knows how to call a method inspite of having the same name on the basis of the parameters passed into the method.
IMP: Overloading cannot be done on the basis of different return types. Return Type itself is not sufficient for overloading of methods. It can only be done on the basis of different type and order of parameters. To explain the above point, have a look at the following code.
Code class Test32 {
public static void main(String[] args) {
Test32 x = new Test32();
x.met1(10);
x.met1(20);
} int met1(int a) {
System.out.println("Method with return type as int");
}
void met1(int a) {
System.out.println("Method with return type as void");
} }
Output
Test32.java:15: met1(int) is already defined in Test32 void met1(int a)
^
1 error
Since overloading cannot be done on the basis of the return type and also the parameters are the same, the compiler is complaining that we already have a method with the same name, as we cannot have the same identifier used twice.
Overloaded Constructors
Overloading is the basic feature of OOPs wherein you have the same method / constructor name but different type and order of parameters.
Let us take the example of a website where in you need the users to input their name and salary.
There are 4 possibilities in this case
a) User inputs his name but not his salary b) User inputs his salary but his name c) User input both salary and name d) User inputs neither salary nor name.
Now let us see how to we code this. We also want the above data to be there in the table wherein incase there is no name, “unknown” should be there and where no salary is there, 0 should be the amount value.
Code
public class Test29 {
String name;
int salary;
public Test29 (String n, int s) {
name = n;
salary = s;
System.out.println("The name entered is = "+name+" and the salary is = "+salary);
}
public Test29(String n) {
this(n,0);
}
public Test29(int s) {
this("unknown",0);
}
public Test29() {
this ("unknown");
}
public static void main(String arg[]) {
Test29 a = new Test29("ABC"); // user inputting only name Test29 b = new Test29(1000); // user inputting only salary
Test29 c = new Test29("XYZ",20000); // user both name and salary Test29 d = new Test29(); // user inputting neither name nor salary
} } Output
The name entered is = ABC and the salary is = 0 The name entered is = unknown and the salary is = 0 The name entered is = XYZ and the salary is = 20000 The name entered is = unknown and the salary is = 0
IMP: Any call to this, if present, must be the first statement in any constructor.
How argument values are passed.
This is one of the most important and the most confusing part of java fundamentals. The fundamental rule for understanding how argument values are passed is:-
a) Primitive Data Types are always passed by value b) Objects are always passed by reference.
Now what do one mean by how values are passed? This would mean when we declare something in the parameter of a method and when actual argument is given to that method, depending on the whether the argument value is a primitive or a object, the values are actually passed in the method.
In java, all arguments values that belong to one of the basic primitive types are transferred to a method using what is called the pass-by-value mechanism.
All this means is that for each argument value that you pass to a method, a copy is made and it is the copy that is passed and referenced through the parameter name and not the original value.
This implies that if you use a variable of any of the basic primitive types as an argument, the method cannot modify the value of the main variable in the calling program. For example;
Code class Test33 {
public static void main (String arg[]) {
int i = 10;
Test33 t = new Test33();
int z = t.met1(i);
System.out.println("The value of the variable captured from the method is "+z);
System.out.println("The value of the actual method variable is " + i);
}
int met1(int a) {
++a;
return a;
} } Output
The value of the variable captured from the method is 11 The value of the actual method variable is 10
So we can finalize the concept over here that whenever we pass a primitive data type as the argument to the method, it would always be passed by value and the original value remains unchanged. In the above example, what is passed as an argument to the met1() is a copy (value) of i and not the actual i and hence what is returned is 11, caught by int z, while the value of i remains contact at 10.
Passing objects to a method.
Until now we have seen that only simple types are parameters to methods. However it is very common and correct to pass objects to methods. One of the most common use of object parameters involves constructors. Frequently you will want to construct a new object so that it is initially the same as some existing object. To do this, you must define a constructor that takes an object of its class as a parameter.
Passing objects to the parameter is known as call-by-reference. In this method, a reference to an argument (and not the value of the argument) is passed to the parameter. Inside the method, this reference is used to access the actual argument specified in the call. This means that changes made to the parameter will affect the argument used to call.
Code
public static void main (String arg[]) {
System.out.println("Value after second call " + z.a+ " " + z.b);
} }
So we see here that when we pass an object as an argument to a method, then it is passed by reference, which means what is passed is the memory location of the address and any changes made in the method also gets reflected in the original also.
Access Modifiers
We have already studied about encapsulation, which links data with the code that manipulates it.
Encapsulation also provides another important feature and that is Access Control. It is through encapsulation that you can control what parts of the code (that is variables and methods) can be accessed by members of other classes which call upon code from your class.
There are 4 types of access control modifiers which can be used to control the visibility of the methods and class variables.
a) public b) private
c) default (when we do not write any modifier also called as friendly) d) protected
We will explain over here the first two modifiers and the other two modifiers are associated with the concept of packages and hence we will be covering the same in the other sub-module.
Public Access Modifier
When a member of a class is having a public access modifier then that member can be accessed by any other code in your program. Remember our original program whether we had used public access modifier in our main (). This is done so to enable the code outside the program – that is the Java run-time system to call it.
Private Access Modifier
There are many situations when we want some data members or methods which access those data members to be accessed by that class and not to be accessed by any other class either by way of inheritance or by way of creation of objects. This can be done by prefixing the members of the class with the keyword private.
The variables / methods prefixed with the private access modifier can be used only within that particular class. Other classes, which extend this class, also cannot access these variables. This keyword provides the maximum security.
For Example
class Test {
public static void main (String arg[]) {
int i = 10 private int j = 10 }
}
class Test1 extends Test {
public static void main (String arg []) {
System.out.println (j); // it is not possible to access j since it is private.
} }
With the help of the above code we can generalize that the private keyword class variable is accessible only with the class in which it was created and not even in the sub-class of that method.
Protected Access Modifier
If a variable or a method is prefixed with this modifier then it will be accessible to all classes in the same package as well as in another class in another package provided the following two conditions are met:-
a) The class in the other package extends the original class b) An instance of sub class is created.
Default Access Modifier
If a class or a method or a variable do not have any access modifier, then it is called as default or friendly access modifier. The visibility of this modifier is in all classes in the same package, either by creating an instance or by virtue of inheritance.
Example:
Now we are going to create two packages and two classes in each of the packages and show the usage of all the above modifiers.
package one;
public class Pack1 {
static private int x=10;
static int y;
static protected int z=30;
}
package one;
public class Pack2 extends Pack1 {
public static void main(String[] args)
{
System.out.println(y);
System.out.println(z);
} }
package one;
public class Pack3 {
public static void main(String[] args) {
Pack1 p=new Pack1();
//System.out.println(p.x);
System.out.println(p.y);
System.out.println(p.z);
} }
package two;
import one.*;
public class Pack4 extends Pack1 {
public static void main(String[] args) {
Pack4 a=new Pack4();
System.out.println(a.z);
Pack1 x = new Pack1()// will give an error System.out.println(x.z); // will give an error }
}
Note: For further explanation, you need to call Prof. Venkat Krishnan on 98214-22745
static Initializing block
As we already know a block is a code which is enclosed in a set of braces so that it is executed together.
A initialization block is a block of code between braces that is executed before an object of the class is created. This is normally used with the static keyword and this block is executed once when the class is loaded.
The main purpose of the static initialization block is:
a) To initialize static data members of the class.
b) To load the library files of other languages so that the same can be used within the java using native keyword. (this is not a part of the java certification).
All the other methods are initialized after the static initialization block. If you want your variables to be started with a particular values, then you can put the same in the static initialization block and can then use the variables in the other methods.
Incase there are multiple static initializing block, then they are executed in the order of their appearance and the static class variables take the value as present in the last block.
Code
class Test35 {
static int a;
static {
a = 10;
}
public static void main(String[] args) {
System.out.println(a);
}
static {
a = 50;
} }
Output 50
This would be 50 because, initially in the first static block it got initialized to 10 and then it again got initialized to 50 before entering the main block. Pls remember that all static blocks would be executed before entering the main method.
Please remember that inside the static blocks do not again declare the variable and incase you do that, then it would be taken as another variable and not the class variable. See the following code for this purpose.
Code
class Test35 {
static int a;
static {
a = 10;
}
public static void main(String[] args) {
System.out.println(a);
}
static {
int a = 50;
} }
Output 10
The output is 10 because in the second static block we are again saying int a = 10 and this a and the class variable a are two different entities.
How Constructors are called
When there is multi level hierarchy, in what order are constructors called. The constructors are called in the order of derivation from superclass to subclass. It is important to note here that this order is followed irrespective of whether super () is used or not. If super () is not used, then the default or parameter less constructor is used. ( we will study about the super keyword in the next sub-module).
Code
class Test36 {
public static void main(String[] args) {
Three x = new Three();
} }
class One {
One() {
System.out.println("Constructor in One class");
} };
class Two extends One {
Two() {
System.out.println("Constructor in Two class");
} };
class Three extends Two {
Three() {
System.out.println("Constructor in Three class");
} };
Output
Constructor in One class Constructor in Two class Constructor in Three class
This would prove that the original constructor of the super most class is loaded first and then it goes down the hierarchy. This is logical since the methods of the super class can be called with the sub class instance variable and hence the super class should be loaded in the memory. By calling the constructor of the super class that class is loaded in the memory.
Please note that the sub-most class would call its super class default constructor which in turn will call the constructor of its super class and this process will go on till the super most classes’
constructor is loaded.
Now incase if there is no default constructor anywhere in the hierarchy then the loading of the classes would stop and a compilation error would be generated. This is why we had insisted earlier that when we define our own constructors, it is our duty to also provide for a default constructor also.
Code
class Test36 {
public static void main(String[] args) {
Three x = new Three();
} }
class One {
One() {
System.out.println("Constructor in One class");
} };
class Two extends One {
Two(int a)
{
System.out.println("Constructor in Two class");
} };
class Three extends Two {
Three() {
System.out.println("Constructor in Three class");
} };
Output
Test36.java:28: cannot resolve symbol symbol : constructor Two ()
location: class Two { ^
1 error
What the compiler is trying to tell us by the above error is that it cannot find a default constructor in class Two. We can make the code compile properly by provide for a default constructor.
is - a and has - a relationship
In programming language, one often creates a model of something (for example, an employee) and then need a more specialized version of that original model. For example, you might want a model for a manager, which only has more features but is still an employee. The Is-a relationship in java is done with the help of extends keyword which creates a new class from an existing class, by sub-classing it.
For Example:
class Employee {
String name;
int salary;
Date hiredate;
}
class Manager extends Employee {
String department;
}
In the above example, when we sub-class the class Manager, the Manager class will have all the variable and methods that an Employee has. All these variables and methods are inherited from the definition of the parent class. The class Manager then adds additional functionality to itself by defining its own variables and methods.
The has-a relationship comes when a particular variable or method is inside a particular class. For example in the above class Employee, we can safely say class Employee has a name.
So we can safely finalize by saying that is-a relationship is for sub-class and super-class relationship and is for variable inside the class.
super keyword
The super keyword refers to the superclass of the class in which the keyword is used. It only refers to the immediate super class and not up the hierarchy. The super keyword has two general forms:
a) The super keyword is also used to invoke the parent class’s constructor from the child class’s constructor. For this one should use the super keyword in the first line of the child class’s constructor.
IMP: If one uses the super with no argument in the child’s class’s constructor, then this will call the default parent class constructor and if such a constructor is not available in the parent class, then a compile error results.
For Example:
class Employee
{
String name;
pubic Employee (String s) {
name = s;
} }
class Manager extends Employee {
String department;
public Manager (String s, string d) {
When a subclass calls super, it is calling the constructor of its immediate superclass and which constructor to call would depend on the parameters being passed in the super keyword argument.
IMP: We had seen earlier in the order in which constructors are called, the sub class automatically calls the super class default constructor and this is possible because there is a implicit super in the sub class which calls the super classes’ default constructor every time.
Code
class Test38 extends TestTem {
int d;
public static void main(String[] args) {
Test38 l = new Test38(10,20,30);
l.area();
System.out.println("The volume is = "+e);
} }
class TestTem {
int a, b;
TestTem( int x, int y) {
a = x;
b = y;
}
void area()
{
int c = a*b;
System.out.println("The area is = "+c);
} };// end of class Output
The area is = 200 The volume is = 6000
In the above code, we have two variables in one class and another variable in the sub-class. The sub class constructor initializes all the 3 variables, by providing the values and the sub class constructor call the super class constructor which will initialize the two variable in that class and then calls the area and volume methods. We can call the area method also, because the Test38 class extends TestTem class.
The main purpose of the super keyword is to ensure that there is no duplication of efforts and more over when we need to specifically call a super class constructor from inside the child classes’ constructor
IMP: The super keyword incase is there in the constructor should be the first line in the sub classes’ constructor or else the compiler would throw an error.
IMP: The super and this keyword cannot be accessed from inside a static method.
b) The second use of super is to refer to the member variables or methods of the superclass that is hidden by the subclass.
This is also like this, except that it always refers to the superclass of the subclass in which it is used. The syntax for the same is:
super.member. (Here the member can either be a variable or a method)
It is used more in those cases when the variable name of a subclass hides the members by the same name of the superclass. For Example:
class First {
int i;
}
class Second extends First {
int i;
Second (int a, int b)// constructor {
super.i = a;
i = b;
}
void method() {
System.out.println( “ This is superclass i “ +super.i);
System.out.println( “ This is superclass i “ +i);
}
class Super {
public static void main (String args []) {
Second s = new Second(10,25);
s.method() }
}
This example shows how to use the super keyword in the second context.
Method overriding
Overriding is one of the basic features of the Object Oriented Programming. If a method is defined in a subclass that has the same name and return type exactly as that of the superclass
Overriding is one of the basic features of the Object Oriented Programming. If a method is defined in a subclass that has the same name and return type exactly as that of the superclass