Newbie: object casting

Z

Zalek Bloom

I am learning Java and here is my problem:

Lets say we have a simple class:

public class Class1
{
final String s1 = "Class1";
public String getMemberS1(){return s1;}
}

Let say we have another simpler class:

public class Class2 extends Class1
{
final String s2 = "Class2";
public String getMemberS2(){return s2;}
}

Now let say we make definitions:

Class1 a = new Class1() ;
Class1 b = new Class2() ;

Now - the variable "b" - it will have properties as Class1 or Class2?
Why?

I wrote a simple program to test it, and it looks that "b" has only a
method and members as Class1, but I wrote:
Class1 b = new Class2() ;

Can somebody explain this?

Thanks,

Zalek
 
C

Christophe Vanfleteren

Zalek said:
I am learning Java and here is my problem:

Lets say we have a simple class:

public class Class1
{
final String s1 = "Class1";
public String getMemberS1(){return s1;}
}

Let say we have another simpler class:

public class Class2 extends Class1
{
final String s2 = "Class2";
public String getMemberS2(){return s2;}
}

Now let say we make definitions:

Class1 a = new Class1() ;
Class1 b = new Class2() ;

Now - the variable "b" - it will have properties as Class1 or Class2?
Why?

I wrote a simple program to test it, and it looks that "b" has only a
method and members as Class1, but I wrote:
Class1 b = new Class2() ;

Can somebody explain this?

Thanks,

Zalek

You are indeed creating a Class2 object (with all the methods and field of
Class2), but you're handling it as a Class1 object, by declaring it that
way:

Class1 b = new Class2();

If you had declared it like

Class2 b = new Class2();

then you would be able to use the Class2 specific methods.

If you have a object that you declared to be of Class1, but is really a
Class2 object (like b is in this case), you can cast it to the correct
type:

Class2 c = (Class2)b;
//now you can use the Class2 methods on c
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,119
Latest member
IrmaNorcro
Top