Let's learn java programming language with easy steps. This Java tutorial provides you complete knowledge about java technology.

Sunday, 19 February 2017

Inheritance in java

 Inheritance

Inheritance simply means re-usability, inheritance allows a class to use the data members(properties) and member function(methods) of another class.

Inheritance is one of the best features of Object Oriented Programming

Inheritance represents the IS-A relationship between the Superclass and its Subclass, it also known as the parent-child relationship.


Real life example of inheritance

  • suppose there is parent and child relationship, child reuse(inherit) the surname of his father and other qualities.
For example:

Ram Singh               Manav Singh
(parent)          inherit       (child)

Advantages of Inheritance



Some important points

  • The class which gives data members and methods is known as super or parent or base class in inheritance.
  • The class which is taken the data members and methods is known as sub or child or derived a class in inheritance.
Syntax of Inheritance:

class Subclass-Name extends Superclass-Name
{
//data members or fields
//member functions or methods
}

In above syntax extends is a keyword, which is used to extend a class in a class declaration. Basically extends keyword is used to increase the properties and behaviors of child(Sub class) class by using Parent(Super class) class.


Simple Example of Inheritance


class Employee
{
int salary = 20000;
}
class Developer extends Employee
{
int age = 26;
public static void main(String args[])
{
Developer d = new Developer();
System.out.println("salary of developer "+d.salary);
System.out.println("age of developer "+d.age);
}
}

output: salary of developer 20000
              age of developer 26

Here, Employee, is super class and  Developer is a subclass. The relationship between two classes is Developer IS-A Employee i.e Developer is a type of employee class.


Types of inheritance

  • Single Inheritance
  • Multilevel Inheritance
  • Multiple Inheritance
  • Hierarchical Inheritance
  • Hybrid Inheritance

Inheritance in Java
In the above picture, Java supports only three types of inheritance through class. These are single, multilevel, hierarchical inheritance. Multiple and Hybrid inheritance are not supported in java through the class but these are supported through interface concept.


Multiple Inheritance

In the above diagram, Multiple and Hybrid inheritance are not supported in java through the class but it is possible through the interface in java.


1) Single Inheritance

Single inheritance is the simple inheritance, when a class extends another class(Only one class) then we call it as single inheritance. In single inheritance there exists single super class(parent class) and single sub class(child class).


For example:

class Animal
{
void eat()
{
System.out.println("eating");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking");
}
public static void main(String args[])
{
Dog d = new Dog();
d.eat();
d.bark();
}
}

output: eating
              barking


👉 : By default, all the data member and the member function of a parent class are available to the child class, if they are not private.



2) Multilevel Inheritance

For example:

class Animal
{
void eat()
{
System.out.println("eating");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking");
}
}
class SmallDog extends Dog
{
void weep()
{
System.out.println("weeping");
}
public static void main(String args[])
{
SmallDog s =
new SmallDog();
s.eat();
s.bark();
s.weep();
}
}

output: eating
              barking
              weeping


3) Multiple Inheritance

In Multiple inheritance one class extending more than one class. Multiple inheritance is not supported in java through the concept of class, but multiple inheritance is supported in java through the concept of interface. we will learn interface in later.

For example:

class A
{
void show()
{
System.out.println("class A");
}
}
class B
{
void show()
{
System.out.println("class B");
}
}
class C extends A,B
{
public static void main(String args[])
{
C c1 = new C();
c1.show();//now which show() method would be invoked?
}
}

output: compile time error

explanation: To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

consider a scenario where A, B, and C are three classes, the class C extends class A and B, if class A and B have the same method and you call it from child class object, there will be ambiguity to call method of class A and B. Because compile-time error is better than runtime errors, java throw compile time error if you inherit or extends two classes. so whether you have same or different methods there will we compile time error.


4) Hierarchical Inheritance

In Hierarchical inheritance, one parent class will be inherited by many sub(child classes ) classes.

For example:

class Animal
{
void eat()
{
System.out.println("eating");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking");
}
}
class Loin extends Animal
{
void roar()
{
System.out.println("roaring");
}
public static void main(String args[])
{
Loin l = 
new Loin();
l.eat();
l.bark();//compile time error
l.roar();
}
}

output: eating
              roaring


5) Hybrid Inheritance

Hybrid inheritance is not supported by java through class, but it is supported by interface concept.

Read More:

Java Encapsulation with Examples.
Java Abstract Class with Examples.
Java Method Overloading with Examples.
Java Wrapper Class with Examples.
Java Inheritance Programming Interview Questions.
Java Inheritance Interview Questions and Answers.

Share:

Wednesday, 15 February 2017

this keyword in java

 this keyword

'this' is a reference variable that refers to the current objects or instance of any class. 'this' is a special keyword in java represent current class object.


this keyword in java



Usage of this keyword in java

There can be lots of usage of java this keyword.
  • this can be used to refer current class instance variable.
  • this() can be used to invoke current class constructor.
  • this can be used to invoke current class method(implicitly).
  • this can be passed as an argument in the constructor call.
  • this can be passed as an argument in the method call.
  • this can be used to return the current class instance from the method. 


1) this can be used to refer current class instance variable

this keyword can be used to refer the current class instance variable. If there is ambiguity between instance variables and formal parameters of a class, this keyword resolve this problem of ambiguity easily.


Problem without this keyword

class Students
{
int id;
String name;
Students(int id, String name)
{
id = id;
name = name;
}
void display()
{
System.out.println(id+" " +name);
}
public static void main(String args[])
{
Students s = new Students(1, "varun");
Students s1 = new Students(2, "rahul");
s.display();
s1.display();
}
}

output: 0 null
              0 null

This above example produce default values(0, null) of instance variables(data members) or objects because there is instance variable and parameters are same, so we are using this keyword to distinguish instance variable or parameters(local variables), so that we can achieve desired output.


Solution of the above problem by this keyword


class Students
{
int id;
String name;
Students(int id, String name)
{
this.id = id;
this.name = name;
}
void show()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Students s = new Students(1,"rahul");
Students ss = new Students(2,"manav");
s.show();
ss.show();
}
}

output: 1 rahul
              2 manav

There is no need of this keyword, If instance variables and parameters(local variables ) are different. For example


class Employees
{
int id;
String name;
Employees(int i, String n)
{
id = i;
name = n;
}
void show()
{
System.out.println(id+""+name);
}
public static void main(String args[])
{
Employees e = new Employees(100,"manav");
Employees ee = new Employees(101,"raghav");
e.show();
ee.show();
}


output: 100 manav
              101 raghav

2) this() can be used to invoke current class constructor 

this() which can be used to call one constructor within the another constructor without  creation of objects multiple times for the same class. In other word this() is used to constructor chaining. 

Syntax: 

this();//for calling default constructor
this(value1, value2....);//for calling parameterized constructor



Rules to use this()

this() always should be the first statements of the constructor. One constructor can call only other single constructor at a time by using this(). 

class Add
{
Add()
{
System.out.println(" default or no parameterized constructor");
}
Add(int i)
{
this();//calling default constructor
System.out.println(" One parameterized constructor");
}
Add(int i, int j)
{
this(10);//calling one parameterized constructor
System.out.println(" two parameterized constructor");
}
}
class thisDemo
{
public static void main(String args[])
{
Add a = new Add(20,30);
}
}

save Add.java
javac Add.java
java thisDemo

output: default or no parameterized constructor
             One parameterized constructor
             two parameterized constructor

you can't use this() in second statement or second line in any constructor.

For example:

class This
{
This()
{
System.out.println("default constructor");
}
This(int i)
{
System.out.println("parameterized constructor");
this();//compile time error
}
public static void main(String args[])
{
This t = new This(10);
}
}

output: compile time error: call to this must be first statement in constructor

3) this can be used to invoke current class method

by using this keyword you can invoke the method of the current class. If you do not use the this keyword, compiler automatically add this keyword at time of invoking of the method.

class A                                                                  class A
{                                                                            {
void b()                                                                 void b()
{   }                                                                       {   }
void c()                                                                  void c()
{                                                                             {
b();                               →            compiler    →       this.b();
}                                                                              }
psvm(String args[])                                              psvm(String args[])
{                                                                              {
new A().c();                                                            new A().c();
}                                                                               }
}                                                                               }


class A
{
void b()
{
System.out.println("this is b");
}
void c()
{
System.out.println("this is c");
b();//b() same as this.b(),no need to use this here compiler does it
}
public static void main(String args[])
{
A a= new A();
a.c();
}
}

output: this is c
             this is b

4) this can be passes as argument in method call

this keyword can be passed as an argument in method.

class Men
{
void a(Men m)
{
System.out.println("i am a");
}
void b()
{
System.out.println("i am b");
a(this);
}
public static void main(String args[])
{
Men m = new Men();
m.b();
}


output: i am b
              i am a

5) this keyword can be used to return current class instance

we can return this keyword as an statements from the method but return type of the method must be the class type.

class A
{
A getA()
{
return this;
}
void show()
{
System.out.println("this is show");
}
public static void main(String args[])
{
new A().getA().show();
}


output: this is show

6) Let's check this keyword that refer to current class instance variable or not

In this example, we are printing reference variable and this ,output of both variable will be same.

class A
{
void show()
{
System.out.println(this);
}
public static void main(String args[])
{
A obj = new A();
System.out.println(obj);
obj.show();
}


output: A@24273305
              A@24273305
Share:

Saturday, 11 February 2017

Method Overloading in Java

 

Method Overloading

Method overloading is a feature that allows a class to have two or more methods having same name, but different number of parameters or different types(Data types) of parameters or different order of parameters, It is known as Method Overloading.

Method overloading is also known as static polymorphism. We can achieve method overloading by using this static polymorphism. Method overloading is done at compile time. The best example of method overloading in the world is System.out.println() method which is overloaded to accept all kind of data types in java. There are println() method which takes int, float, double, String etc.


Method Overloading In Java



Why use method overloading in java?

Suppose we have to perform addition of given number but there can be any number of arguments, if we write method such as x(intint) for two arguments and y(int, int, int) for three arguments than it is very difficult for your and other programmers to understand purpose or behavior of method, they can't identify purpose of method. So we use method overloading concept to easily figure out the program.

for example above two methods x and y we can write sum(int, int) and sum(int, intint) using method overloading concept.


Advantage of method overloading in java

  • Method Overloading increases the readability of program.
  • Overloaded method are fast because they are bounded during compile time and no check or binding is required at run time.


Different ways to Overload the method

  • By changing number of arguments or parameters.
  • By changing the data type.

👉 : Method Overloading in java is not possible by changing the return type of the method.

Syntax 1:

class ChangingNoOfArguments
{
returnType methodName()//There is no arguments in method
{
--------
--------
}
returnType methodName(datatype1 variable1)//There is 1 argument 
{
--------
--------
}
returnType methodName(datatype1 variable1, datatype2 variable2)
{
-------
-------
}
}

Syntax 2:

class ChangingDataType
{
retrunType methodName(datatype1 variable1)//e.g methodName(int i)
{
-------
-------
}
retrunType methodName(datatype2 varibale2)//e.g mName(float f) 
{
-------
-------
}
}


1) Example Method Overloading by changing no. of arguments

Now here, we have created two overloaded methods first method 'sum' performs addition of two numbers and second method 'sum' performs addition of three numbers.

class Addition
{
void sum(int a, int b)
{
System.out.println(a+b);
}
void sum(int a, int b, int c)
{
System.out.println(a+b+c);
}
public static void main(String args[])
{
Addition a = new Addition();
a.sum(10,20);
a.sum(20,30,40);
}
}

output: 30
              90

Another example of method overloading by changing no. of arguments. here in this example we have created two methods, first method 'sum' perform addition of two number and second method 'sum' perform addition on three number but here we have created static methods so that we don't need to create instance to calling methods.

class Addition
{
static int sum(int a, int b)
{
return a+b;
}
static int sum(int a, int b, int c)
{
return a+b+c;
}
}

class Overloading1
{
public static void main(String args[])
{
System.out.println(Addition.sum(10,20));
System.out.println(Addition.sum(100,200,300));
}
}

save Addition.java
javac Additon.java(compile)
java Overloading1(run)

output: 30
              600


2) Example Method Overloading by changing the data type of argument

In this example, we have created two overloaded methods that differs int data types. The first method 'sum' receives two integer arguments and the second method 'sum' receives two float arguments.

class Addition
{
void sum(int a, int b)
{
System.out.println(a+b);
}
void sum(float a, float b)
{
System.out.println(a+b);
}
public static void main(String args[])
{
Addition a = new Addition();
a.sum(10,20);
a.sum(10.5,20.5);
}
}

output: 30
              31

Share:

Facebook Page Likes

Follow javatutorial95 on twitter

Popular Posts

Translate