Welcome to the fifth part of our core Java series. In the last part, we discussed arrays, string and StringBuffer Class. If you are new, please check out the previous articles. In this post we’ll discuss object-oriented programming in Java. Let’s get started.
If a problem is solved in terms of classes and objects, it is called object-oriented programming.
A class provides definition for an object. An object is known as an instance of the class. A class contains two parts - private and public.
In general, the private part contains variables and it is not accessible to the user. Similarly, methods form the public part of the class which is accessible to the user.
Let’s use an example where we’ll create a class and use its objects.
1
2
3
4
5
6
7
8
9
10
11
12
13
class Money {
private int rs;
private int paise;
public void set(int r, int p) {
rs = r;
ps = p;
}
public void display() {
System.out.println(rs + "." + paise);
}
}
Save this file as Money.java
Now let’s see another example which will utilize this class.
1
2
3
4
5
6
7
8
9
class UseMoney {
public static void main(String args[]) {
Money m;
m = new Money();
m.set(20, 40);
System.out.println("Amount is:");
m.display();
}
}
When we compile and run this file, it will create an object of Money class and set (20,40) values in its variables (rs,paise). When we call display method it will give the output values on the console.
Method overloading is an example of compile time polymorphism that means the same method name can be used with different numbers of arguments (One name many forms
).
A class can contain any number of methods as long as their signatures are different. Signature is nothing but method name and arguments all together.
A class can contain multiple methods with the same name as long as their arguments are different. This is called method overloading
.
Either the number of arguments, the type of arguments or the order of arguments must be different.
Let’s see an example -
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Calculator {
public int sum(int a, int b) {
return a + b;
}
public int sum(int a, int b, int c) {
return a + b + c;
}
public float sum(float a, float b) {
return a + b;
}
public float sum(int a, float b) {
return a + b;
}
public float sum(floar a, int b) {
return a + b;
}
}
class Application {
public static void main(String args[]) {
Calculator calc = new Calculator();
int x;
float a;
x = calc.sum(1, 2);
System.out.println(x); // Output will be 3
a = calc.sum(1.5 F, 2.7 F);
System.out.println(a); // Output will be 4.2
}
}
In this example, if we want to get the sum of more than three arguments we can use variable length arguments
. Let’s see an example.
1
2
3
4
5
6
7
8
class Calculator {
public int sum(int...abc) {
int total = 0;
for (int x = 0; x < abc.length; x++)
total += abc[i];
return total;
}
}
Only one variable length argument is allowed in a function and it should be the last formal parameter.
1
2
3
public void method(String s, float a, int...b) {
...
}
It reduces the number of methods in a class if method overloading is being done on the basis of the number of parameters.
This
is a reference variable which refers to an object that has called the member function. This
variable is created automatically so we don’t need to declare it. It is available in all the methods of the class except static methods.
1 2 3 4 5 6 7 8 9
class Money { private int rs; private int paisa; public void set(int rs, int paisa) { this.rs = rs; // it will set the value of private variables this.paisa = paisa; } }
These are special methods that are called automatically when an object of the class is created. Constructors have the same name as the class. They don’t have any return type, not even void (If we define return type then it will be considered as a method).
There are three types of constructors -
Default Constructor - This constructor takes no arguments and it is called when an object is created without any explicit initialization, e.g.
Money m1 = new Money();
Parameterised Constructor - It is called when an object is created and is initialized with some values at the time of creation, e.g.
Money m2 = new Money(100,20);
Copy Constructor - It is called when an object is created and is initialized with some other object of the same class at the time of creation, e.g.
Money m3 = new Money(m2);
NOTE - If we don’t define any of the constructors then a default constructor will be provided by Java. But if we define any of the constructors then Java will not provide any constructor.
A constructor is called once for an object in its lifetime when it is created.
By using this()
a constructor can be called from another constructor of the same class as a method name. A call to this()
must be the first executable statement of the construction otherwise there will be compile time errors.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Point3D {
private int x, y, z;
public Point3D(int a, int b, int c) {
x = a;
y = b;
z = c;
}
public Point3D(int a, int b) {
this(a, b, 0);
}
public Point3D(int a) {
this(a, 0, 0);
}
public Point3D(Point3D p) {
this(p.x, p.y, p.z);
}
}
Only one this()
can be called in one constructor.
Constructors cannot be recursive or cyclic, e.g.
1
2
3
public int Point3D(int a, int b) {
this(a, b);
}
Inheritance means to derive a class from another class. The derived class has features of base class plus its own additional functionality. In Java, we use extends
keyword to inherit a class. For example -
1
2
3
4
5
6
7
8
9
10
11
12
class A { // Super class
int x, y; // inherited members
...
...
}
class B extends A // sub class
{
int z;
...
...
}
An inherited member is that member of a superclass that is accessible to the methods of the sub class.
Super class variables that are not inherited (i.e. private variables) still form part of the sub-class object and we can refer to them indirectly through the public methods that have been inherited.
Example -
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class A {
private int x;
public void setX(int a) {
x = a;
}
public void showX() {
System.out.println(x);
}
}
class B extends A {
private int y;
public void setXY(int a, int b) {
setX(a);
y = b;
}
public void showXY() {
showX();
System.out.println(y);
}
}
class demo {
public static void main(String args[]) {
B b = new B();
b.setXY(1, 2);
b.showXY();
}
}
If the superclass and subclass both have methods with the same name, same argument lists and same return types, it is called method overriding.
If the superclass and subclass both have methods with the same name and same argument list then their return type must also be the same otherwise it will lead to a compile time error.
Instance methods can override instance methods and static methods can override static methods.
While overriding a method, the overridden method in the subclass can be less restricted (protected to public) but it cannot be more restrictive (protected to private)(compile time error).
NOTE - Multiple inheritance of classes are not allowed in Java.
1
2
3
4
class A extends B, C // error
{
...
}
If a method has no definition then it is called abstract method
and it must be declared using a keyword abstract
otherwise it will lead to a compile time error.
If a class includes one or more abstract methods then it is called an abstract class
and it must be declared using the keyword abstract
otherwise there will be a compile time error.
When a class extends an abstract class then it must define all the abstract methods.
Example -
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
abstract class Animal {
abstract public void speak();
abstract public void move();
}
class Dog extends Animal {
public void speak() {
System.out.println("Bark!!!");
}
public void speak() {
System.out.println("Run!!!");
}
}
class Cat extends Animal {
public void speak() {
System.out.println("Meow!!!");
}
public void speak() {
System.out.println("Walk!!!");
}
}
Abstract methods cannot be private since private methods are never inherited.
Abstract methods/class cannot be final.
Constructors cannot be abstract because constructors are never inherited.
An interface is known as a collection of abstract methods and constants.
A class is inherited whereas an interface is implemented.
In an interface methods are public and abstract by default and variables are public, static and final by default.
We cannot create an object of an interface but we can create a reference variable. This reference variable can refer to objects of all those classes that implement the interface.
In an abstract class some of the methods might be defined but in interface all the methods are abstract.
An interface can extend another interface unlike classes where multi-inheritance is not allowed.
Example -
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
interface Animal {
void speak();
void move();
int NO_OF_LEGS = 4;
}
class Dog implements Animal {
public void speak() {
System.out.println("Bark");
}
public void move() {
System.out.println("Runs");
}
}
class Cat implements Animal {
public void speak() {
System.out.println("Meow");
}
public void move() {
System.out.println("Walks");
}
}
class Home {
public static void main(String args[]) {
System.out.println("Our pets have " + Animal.NO_OF_LEGS + " legs");
Animal a; // interface reference variable
a = new Dog();
a.speak(); // Output: Bark
a.move(); // Output: Runs
a = new Cat();
a.speak(); // Output: Meow
a.move(); // Output: Walks
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
interface x {
void a();
void b();
}
interface y {
void c();
void d();
}
interface z extends x, y { // Contains methods of x and y both
void e();
void f();
}
class Demo implements z {
// All 6 methods has to be defined
}
That’s all for now. Now it’s your turn to try what you learned in this blog post. Happy coding :)