77 Program on Up-casting & Down-casting in Java?

Code:

import java.util.Scanner;

class A
{
int a = 111 ;
static int b =222;

void m1()
{
System.out.println(" Super class non static m1 method ");
}

static void m2()
{
System.out.println(" Super class static m1 method ");
}
}

class B extends A
{
int a = 333;
static int b = 444;

void m3()
{
System.out.println(" Sub class non static m3 method ");
}

static void m4()
{
System.out.println(" Sub class static m4 method ");
}

void m1()
{
System.out.println(" Sub class non static m1 method ");
}

static void m2()
{
System.out.println(" Sub class static m1 method ");
}
}

public class Test
{
public static void main( String args[] )
{
A obj = new A();
System.out.println( obj.a );
System.out.println( obj.b );
obj.m1();
obj.m2();

System.out.println("------------------------------------------------");
B obj2 = new B();
System.out.println( obj2.a );
System.out.println( obj2.b );
obj2.m1();
obj2.m2();

System.out.println("------------------------------------------------");
A obj3 = new B(); // Upcasting
System.out.println( obj3.a );
System.out.println( obj3.b );
obj3.m1();
obj3.m2();

System.out.println("------------------------------------------------");
B obj4 = (B) obj3 ; // Downcasting
System.out.println( obj4.a );
System.out.println( obj4.b );
obj4.m1();
obj4.m2();

}
}


Output:


Previous
Next Post »