Web technology

web developers learning site

Archive for the category “java”

Typecasting of object in java programming

class A{
int a = 5;
void test()
{
System.out.print(“A”);
}
}
class J extends A{
int a = 10;
void test(){
System.out.println(“J”);
}
}

public class M extends J  {

int a = 15;
void test()
{
System.out.println(“M”);
}
public static void main(String args[])
{
J obj = new M();
M k = (M)obj;
A a = (A)k;

System.out.println(obj.a +”  “+k.a + ”  “+a.a);
k.test();
a.test();
}
}

 

Output ::

10  15  5
M
M

 

Static block and block in java

Static block – Firstly executed (Without create instance)
Block – Secondly executed (After creating instance of class)
Constructor – Thirdly Executed

class A{
int a = 5;
A(){System.out.println(“Constructor”);}
{System.out.println(“Block”);}
}
class J extends A{
static{System.out.println(“Static block”);}
int a = 10;
void test(){
System.out.println(“J”);
}
}
class M extends J  {
int a = 15;
void test(){
System.out.println(“M”);
}
public static void main(String args[])
{
System.out.println(“Test”);
J obj = new M();
System.out.println(obj.a);
obj.test();
}
}

Program Output ::

Static block
Test
Block
Constructor
10
M

Post Navigation