Friday, 15 December 2017

Overloading and Overriding

Overloading-

public class Overloading {
public static void main(String[] args) {
Parent p = new Parent();
p.check();

Child c = new Child();
c.check();
c.test();

Parent pc = new Child();
pc.check(); // call only parent methods coz object refer by parent reference

//here pc reference point to Child obj, So we pc can be casted to Child. Now we can access both parent and Child obj mothods
((Child)pc).check();
((Child)pc).test();

p = c; // Child obj can be refered by parent reference
p.check();

}
}

class Parent {
void check() {
System.out.println("-- Check --");
}
}

class Child extends Parent {
void test() {
System.out.println("-- Test --");
}
}

Overriding - 

package com.qt;

public class OverridingTest {

public static void main(String[] args) {
ParentCls p = new ParentCls();
p.check(); // -- Check -- Parent

ChildCls c = new ChildCls();
c.check(); // -- Check -- Child
ParentCls pc = new ChildCls();
pc.check(); // -- Check -- Child
((ChildCls)pc).check(); // -- Check -- Child
ParentCls pp = c;
pp.check(); // -- Check -- Child
// We can use super inside child class overriden method to parent class methods by using child class object. 
}

}


class ParentCls {
void check() {
System.out.println("-- Check -- Parent");
}
}

class ChildCls extends ParentCls {
void check() {
System.out.println("-- Check -- Child");
}
}

No comments:

Post a Comment