HTML Java

Java Inheritance


Inheritance

Inheritance simply means child inherits behavior and properties from parent.

Benefits:
  • Code Reusablility
  • Avoid code duplicacy
  • Reduce Complexity
  • Runtime Polymorphism
  • Method overriding
  • Data Hiding


Reusability in java

Real life example like our laptop battery is discharge the charge it and reuse it.

Like Gas cylinder if empty then we refill it again. To save cost same thing in coding.

Reusablity
  • Association (has-A)
    • composition(Strong)
    • Aggregation(Weak)
  • Inheritance (is-A)

Without relation reusability is not possible.

Benefits of reusability in code is 1 already developed program used in another program. To avoid ambiguity in code


Car is a vehicle and bike is also vehicle and when you got the relation is (is-a) then always prefer for inheritance. If relation is (has –a) then go for association.

Car has a (engine, MusicSystem)When between 2 classes relation is (has-a) then use association.

But when we remove the engine then car become useless then its example of composition.

Music system has a relation with car but its an aggregation without music system we can have car.


In Coding we create constructor for strong and methods for weak things like we have an example of human, human have hair, heart, eyes human can live without hair but not without heart.

Hand Class

class Hand {
void hand() {
System.out.println(“Hand is weak”);
}
class Heart {
Heart() {
System.out.println("Heart is Strong");
}
}
}

Human class

class Human {

Hand hand; // aggregation in java
Heart heart;

Human() {
Hand=new Hand(); //composition in java
new Heart(); //association in java
}

public static void main(String args[]) {
Human h = new Human();
h.hand.hand(); //OGNL(object graph navigation language) in struts
}
}


Example of Inheritance



Whenever we create any class in java then it’s impossible to create without inheritance because implicitly we are inheriting Object Class implicitly. Means every class extending Object class and this is Super class for every class.

Ways to Access non static data or method
  • You can create an object of this class inside the class.
  • Create reference of this class and access it
  • Or by creating and constructor or in non-static method.

It’s a same class access approach now we use another way to accessing that data member and method by inheriting the class.

Note :

non static data get memory when object is created.

So create 1 child class


Then question is ,How can we access non static data inside any static method. Now you can access similar in child class as well.

Example:

class Child extends Parent {
public static void main(String args[]) {
Child c =new Child ();
System.out.println("Show Child x:"+new Child ().x);
System.out.println("Show Child x:"+c.x);
}
}


Example:

class Parent{
int x=10;
Parent(){
show();
display();
}
void show() {
System.out.println("Show Parent");
}
void disp(){
System.out.println("Display Parent");
show();
}
static void display() {
System.out.println("Show Parent");
//show(); but not in static method
}
}


Example:

class Child extends Parent {
private static int y=4;
static int z=5;
Child() {
System.out.println("Show Child x:"+x);
show();
display();
hiChild();
}
void hiChild() {
System.out.println("Show Child x:"+x);
show();
display();
}
static void helloChild(){
System.out.println("Hello Child");
}
public static void main(String args[]) {
Child c =new Child ();
Parent p =new Child(); //A good Programming
// Its a bad Programming Parent p =new Parent();
System.out.println("Show Child x:"+new Child ().x);
System.out.println("Show Child x:"+c.x);
//show();but not in static method
//display();but not in static method
//hiChild();but not in static method
System.out.println("Show Child x:"+new Child ().x);
//c.show();
//c.display();
//c.hiChild();
//System.out.println("Show Child x:"+p.y);
//p.hiChild();
//p.helloChild();
}
}

Note:This is how can we access non-static method and data member in a class or outside the class by inheritance child can access all data member and method parent but not private and Parent can’t anything of child data member and method.



When in above program Parent want to access it child data or method then we will get an error.
//System.out.println("Show Child x:"+p.y);
//p.hiChild();
//p.helloChild();

When Parent class don't access child class data then it will happily run



Ques: How to Access static data member or method in a class and in child?

Sol:

class Parent{
static int x=4;
Parent(){
display();
}
void show() {
System.out.println("Show Parent :"+x);
display();
}
static void display() {
System.out.println("Static Show Parent");
System.out.println("Show Parent :"+x);
}
}

Example:

class Child extends Parent {
Child() {
display();
}
void hiChild() {
System.out.println("Show Child x:"+x);
display();
}
public static void main(String args[]) {
Child c =new Child ();
Parent p =new Child(); //A good Programming
c.display();
display();
new Child().display();
Parent.display();
p.display();
Child.display();
}
}


Ques: What is Data Hiding?

Sol: It simply means when we declare a variable in parent class suppose name x=10 and with the same name we declare variable in child class X=20 then when we print x then you will see that output will be 20 because child data hides the parent data . Its similar to Data shadowing, but here is 1 difference that data shadowing happen in 1 class but data Hiding happened in 2 class parent and child.

Note: whenever data hiding is done always preference goes to child class data.



Ques: What is data shadowing?

Sol: When in a class instance variable name and local variable name same then preference goes to local variable it’s called data shadowing. When this shadowing between 2 class then its call data hiding.

Example of Data Hiding and Data Shadowing



Super Keyword

It’s a Keyword in java which can be used in so many ways.

  • its use to identify the immediate parent class data in case of data hidiing.
  • its use to identify parent and the parent class method in case of method overriding.
  • its used to call the immediate parent class constructor in case of constructor chaining.

Note : super keyword not be used in static context(static method or static block) like this keyword .

Example of super Keyword



Upcasting

In java there is rule that object of child class can be hold in reference variable of Parent class this concept is called Upcasting.


Down casting

In java there is rule that object of Parent class can be hold in reference variable of Child class this concept is called Upcasting.

Note: without upcasting downcasting is not possible.



Ques: What is Method Overriding?

Sol: Suppose we have 2 class 1 Parent and 1 child classes and when a parent have any method and the method same name is also present in child class with same type and Signature then its called method Overriding.

Note: Whenever method overriding is done always preference goes to the child class Overridden method.



Ques: Why we use method overriding concept ?

Sol: Because to reuse code .when child wants all what in base logic and base concept as its but enhancement in child that is called Method overriding. You can see in the program. Here in vehicle start Method is and in Car class show method is enhance so you can say Car override method of Vehicle and its concept is called method overriding.

Example:

class Vehicle{
void start(){
System.out.println("Vehicle is running");
}
}
class Car extends Vehicle {
void start(){
System.out.println("Vehicle is running @ 150 Speed") ;
}
public static void main(String args[]) {
Car c =new Car();
c.start();
}
}


Method overloading

Method overloading we can achieve in same class or in the case of Parent and child class.

Example:

class Vehicle {
void start() {
System.out.println("Vehicle is running");
}
}
class Car extends Vehicle {
void start(int speed) {
System.out.println("Vehicle is running @ 150 Speed : "+speed);
}
public static void main(String args[]) {
Car c =new Car();
c.start(); // when your write also this in program c.start(120);
}
}

Output

when you call method with an arguement as 120 c.start(120); then it will call methods which is define in the child class.

Output



Only change with return type you cannot achieve method overriding.

Example:

class Vehicle {
void start() {
System.out.println("Vehicle is running");
}
}
class Car extends Vehicle {
int start() {
System.out.println("Vehicle is running @ 150 Speed : "+speed);
}

public static void main(String args[]) {
Car c =new Car();
c.start();
}
}

You will get compile time error because you are changing only return type and you want method overriding.then its not possible.

Output

Note: Any class default value is null.



Ques: Can Method Overriding achieve by changing in return type too?

Sol: But after jdk 1.5 you can achieve method overriding by changing only return type but condition is return type should not primitive type.

So what we done here we create relation between A and B in Vehicle class Return type is A so we make class A parent and B class child And B is return type of Car class so according to this we create relation ship between them and A and B are covariant because it’s a return type of Vehicle and Car in method overriding case and we can return null. Or return an object.

Example:

class A {
}
class B extends A {
}
class Vehicle {
A start() {
System.out.println("Vehicle is running");
return null;
}
}
class Car extends Vehicle {
B start() {
System.out.println("Car is running @ 150 Speed : ");
return new B();
}
public static void main(String args[]) {
Car c =new Car();
c.start();
}
}

You can see here method overriding is happen. By using covariant type and changing only return type.


Example of covariant type, method overriding and method chaining

Example:

Vehicle start() {
System.out.println("Vehicle is running"); {
return this;
}
}
class Car extends Vehicle {
Car start() {
System.out.println("Car is running @ 150 Speed : ");
return this;
}
void display() {
System.out.println("Covariant Types : ");
}
public static void main(String args[]) {
Car c =new Car();
c.start();
c.start().display();
new Car().start().display();
}
}


Constructor chaining

It is the process of calling multiple constructors in a chain when object is created.

There are 2 ways to achieve constructor chaining.
  • super keyword [ super(); ]
  • this keyword [ this(); ]

Note: Both the keyword must be written in the first line of constructor body.

Rule: when we use super in child class constructor then Jvm ,before executing child class constructor first execute the immediate Parent class default constructor not parameterized constructor.



Ques: Why its first execute Parent class constructor?

Sol: Because in order to initialize parent class Data member.

If we have multiple constructor in child class and want to call the default constructor of the Parent class, then we have to use super in every constructor. if we don’t use then compiler add implicitly. Because we can create object using any constructor either parameterized or non parameterized so , that’s why we write super keyword at the top of every constructor in child class . when we compile the java file then Compiler add super keyword at the top of every constructor in child class at compile time ,to call default constructor of parent class.

If we create parameterized constructor in parent class ,but we did not define any default constructor. And child class constructor use super keyword in its constructor ,so jvm will executes parent class constructor before executing child class constructor ,but it can call only Default constructor of Parent class and it was not there in Parent class constructor ,so you will get compile time error. Because when you didn’t create any constructor in the Parent class, then compiler add a default constructor in the Parent class ,but you create a parameterized constructor so compiler will not add default constructor so you will get an error. In this example you can see.

Example:

class B extends A {
B(int x) {
System.out.println("Default constructor of B" +x);
}
}
class ConstructorChain extends B {
ConstructorChain() {
System.out.println("Default constructor");
}
public static void main(String args[]) {
ConstructorChain c =new ConstructorChain();
}
}

If you want to call multiple constructor of a same class in a chain ,then you can use this keyword .If we use this keyword at any constructor ,then we can’t use super key word in that constructor.

Example:

class A {
A() {
System.out.println("Default constructor of A");
}
}
class B extends A {
B() {
System.out.println("Default constructor of B");
}
}

Example:

class ConstructorChain extends B{
ConstructorChain(){
this(5);
System.out.println("Default constructor");
}
ConstructorChain(int x){
System.out.println("parameterized constructor"+x);
}
public static void main(String args[]) {
ConstructorChain c =new ConstructorChain();
}
}




Types of Binding.
  • Static Binding(Compile time or earlier Binding).
  • Dynamic Binding(late Binding or runtime Binding).

If a member call getting their member definition at compile time is called Static binding.Compile time binding done by compiler on the behalf of type of Reference variable.

Things which are statically Bind.
  • Data Member(Static or non static).
  • Static,private,final member function.
  • Constructor.
  • Initializers(init block and static block) in java only non static(virtual method) is not static bind..

Dynamic binding :If a member call get their member definition at runtime called dynamic binding.

Runtime binding done by JVM on the behalf of type of object .
  • The virtual method is only dynamic bind.