Code question

  • Thread starter Thread starter Patrick De Ridder
  • Start date Start date
P

Patrick De Ridder

B is an interface
L implements B

What is happening here?
B l = new L (xyz);

Thanks,
Patrick.
 
Patrick De Ridder said:
B is an interface
L implements B

What is happening here?
B l = new L (xyz);


'l' is a reference of type B to an instance of type L. One of the effects
is that, by default, the only members exposed via 'l' are B members and
you'll have to use a cast to access the functionality of L. This is useful
when you have a routine that operates on type B, but the instance can be L
or some other type that implements B.

Joe
 
Patrick said:
B is an interface
L implements B

What is happening here?
B l = new L (xyz);

In addition to being an object of type L, your object is also of type B
so the assignment is legal and valid. Be aware that only the members
exposed by the interface will be available to you. Of course, in a
situation such as this that's most likely what you're after.

--
There are 10 kinds of people. Those who understand binary and those who
don't.

http://code.acadx.com
(Pull the pin to reply)
 
Is this homework? If so stop reading. :)

Three things are happening:
1) You are creating a new variable that will point to an object implementing
the "B" interface. You will only be able to call methods on this variable
that are in "B" or "B"'s ancestors.
2) You are creating a new object of type "L", passing in xyz to the
constructor.
3) You are assigning the object created in 2) above to the variable of type
"B" from 1) above. Because L implements B (can be treated as a "B"), this
assignment succeeds.

You can now call the interface methods defined in B on this object, which
happens to be of type L without performing any casting.
 
Back
Top