Saturday, May 30, 2015

DifferentType-SameObj

package package1;

public class Class1 {

public String abc() {
System.out.println("Abc Method from Class1");
return "ABCname";
}
}

----------------------------------------------------------------------

package package1;

public class Class2 extends Class1 {

public String xyz() {
System.out.println("xyz method from Class2");
return "xyzNAME";
}
// this abc() method should be commented in first cases
public String abc() {
System.out.println("second abc method from class2");
return "abcFromClass2also";
}
}

-----------------------------------------------------------------------------------------------------------------------

package package1;

public class main extends Class2 {

// CHANGE DATATYPE
// Create an object using another OBJECT TYPE     Ex:  ClassA() objB = new ClassB();
// We can use the type of SuperClass to make the object of the sub class Example: above line
// Case 1:
// Suppose three calsses ClassA ClassB ClassC and 
// B extends A and nnnnnnn C extends B
// In A create methodClassA and create methodClassB in classB
// Now make Ex:  ClassA() objB = new ClassB(); in classC main method and try to fetch the method !!
// We can only fetch method from classA not from ClassB 
// so the output will be print only from the methodClassA of ClassA
// Case 2:
// Suppose three calsses ClassA ClassB ClassC and 
// B extends A and nnnnnnn C extends B
// In A create methodClassA and create methodClassB and methodClassA in classB
// Now make Ex:  ClassA() objB = new ClassB(); in classC main method and try to fetch the method !!
// We can now fetch method from classB not from ClassA
// so the output will be print only from the methodClassB of ClassB
public static void main(String[] args) {
Class2 clas2 = new Class2();

// Print the return syso result as well as return string
System.out.println("---------------------------------------------");
System.out.println(clas2.xyz());
System.out.println("---------------------------------------------");

System.out.println("\n--------------------no another abc() method-------------------------");

// Suppose in this case there is no another abc() method in the Class2 ,
// then the output will show from the abc() method from the class 1

Class1 c2obj = new Class2();
c2obj.abc();
System.out.println("\n-----------------another abc() method i class2 also---------------------");

// Suppose in this case there is an another abc() method in the Class2 ,
// then the output will first check abc() method from class2 
// show from the abc() method body from the class 2 as a result

c2obj = new Class2();
c2obj.abc();
}
}

------------------------------------------------------------------------------------------------------------------------


No comments:

Post a Comment