Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / January 2007

Tip: Looking for answers? Try searching our database.

Problems with inheritance!

Thread view: 
nullstring - 02 Jan 2007 12:38 GMT
Hello together!
Fist of all, HAPPY NEW YEAR!!!
I was hoping the year 2007 doesn't starts with open questions, but so
what... :-)

Ok, to my problem:
public abstract class subject
{
 abstract public void inheritedFuntion();
}
and:
public class object_1 extends subject
{

 public void inheritedFuntion()
 {
   System.out.println("I am inherited from the class subject");
 }

 public void additionalFuntion()
 {
   System.out.println("I am not! I am new here:-)");
 }
}

So, thats my startingposition!!!!
Now I want to do this:
 subject sub = null; //In another class, from where I want to call the
...
                             //...inheritedFuntion() or the
additionalFuntion()
// I don't want to do: object_1 sub = null; because, there are other
kinda object-classes and ...
// ... this abstract reference will be concreted at runtime.

So! Now the point:
   sub = new object_1(); //works fine!! An abstract reference gets
concreted!
But:
  sub.additionalFuntion(); //this method isn't available!
                                     //why? I have a concrete
refenence from type object_1,
                                     //so why I can't call all
object_1-functions???

thanks in advance
Nullstring
ck - 02 Jan 2007 12:51 GMT
> Hello together!
> Fist of all, HAPPY NEW YEAR!!!
[quoted text clipped - 43 lines]
> thanks in advance
> Nullstring

Thats because sub is of type subject and not of type object_1. Java
provides two types of inheritance 1) inheritance by contract 2)
inheritance by implementation.
In 1) subclasses can be used where ever superclasses could be used.
In your example, super class(subject) does not define
additionalFuntion(). Hence cannot invoke the the method on sub.

Hope this helps.
Cheers,
Ck
http://www.gfour.net
nullstring - 02 Jan 2007 13:21 GMT
If I have 5 subclasses (object_1, object_2, .... , object_5) I can hold
5 object-references.
But I don't want to do this....
Is there any possibility, the realize it that way that I wanted it?
(with one reference)

Yeah, that helped, thank you very much!
Nullstring
ck - 02 Jan 2007 13:34 GMT
> If I have 5 subclasses (object_1, object_2, .... , object_5) I can hold
> 5 object-references.
[quoted text clipped - 4 lines]
> Yeah, that helped, thank you very much!
> Nullstring

You can use inheritance through interface in that case. Though you
would need to declare the methods in your interface.
Example:-
interface ObjInterface {
public void meth1();
public void meth2();
public void meth3(); // other methods if there are any without any
concrete implementation
}

public class object_1 implements ObjInterface {
public void meth1() {
 // concrete implementation
}
}

public class object_2 implements ObjInterface {
public void meth1() {
 // concrete implementation
}
}

public class object_3 implements ObjInterface {
public void meth1() {
 // concrete implementation
}
}

So on for rest of the object classes. You can refer to all of them like
mentioned below

public class tester {
 public static void main(String [] args) {
 ObjInterface o1 = new object1(); // you are creating all the objects
of type ObjInterface
 o1.meth1();  // invokes concrete implementation of object_1
 o1 = new object2();
 o1.meth1(); // invokes concrete implementation of object_2
 o1 = new object3();
 o1.meth1(); // invokes concrete implementation of object_3
 }

I think same result can be obtained by extending an abstract or a
concrete class too. Though Interface is a preferred way to design.

Cheers,
Ck
http://www.gfour.net
nullstring - 02 Jan 2007 14:04 GMT
Ok!
But let's say the  methods:
- public void meth1();
- public void meth2();
are all the same, independent on the derivated subclass!

only the method:
- public void meth3();
variates from subclass to subclass....

When I use an Interface, I have to write duplicated code, havent't I?
I know (and read everytime) about "prefer interfaces to abstract
classes", but how can this correlate with "don't write redundant code"
?

thank you very much...
ck - 02 Jan 2007 14:13 GMT
> Ok!
> But let's say the  methods:
[quoted text clipped - 12 lines]
>
> thank you very much...

Actually (much)duplication does not happen, because interface does not
contain any implementation. Though if some of the methods(or many) of
subclasses are going to be same, in that case you can choose to write
abstract class(it depends on how you design your classes). Extending is
considered to be bad because in Java you can only extend one
class(extending also locks you with a specific implementation), though
you can implement more than one interfaces.
You could read about design issues at javaworld. I have a small
collection of them at my blog
http://java-gfour.blogspot.com/2006/12/designing-issues.html
Why particularly extend should be avoided you can read article at
http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html

Hope this helps

Cheers,
Ck
http://www.gfour.net
Oliver Wong - 02 Jan 2007 22:18 GMT
> Ok!
> But let's say the  methods:
[quoted text clipped - 10 lines]
> classes", but how can this correlate with "don't write redundant code"
> ?

public abstract class SuperClass {
 public void methodWhichIsTheSameForAllClasses() {
   /*Some code, not duplicated anywhere.*/
 }

 public abstract void
methodWhichIsPresentInAllClassesButWhoseImplementationDiffers();
}

public class Subclass1 extends SuperClass {
 public void
methodWhichIsPresentInAllClassesButWhoseImplementationDiffers() {
   /*Subclass1 implementation, not duplicated anywhere.*/
 }

 public void methodOnlyPresentInSubclass1() {
   /*Some code, not duplicated anywhere.*/
 }
}

public class Subclass2 extends SuperClass {
 public void
methodWhichIsPresentInAllClassesButWhoseImplementationDiffers() {
   /*Subclass2 implementation, not duplicated anywhere.*/
 }

 public void methodOnlyPresentInSubclass2() {
   /*Some code, not duplicated anywhere.*/
 }
}

   - Oliver
Andrew Thompson - 02 Jan 2007 13:58 GMT
> public abstract class subject

Note that to help others parse your code, it
helps to use the common nomenclature.

That would be along the lines of..

<SSCCE>
package all.lower.case;

public class EachWordUpperCase {

  final String ALL_UPPERCASE = "Constant";
  String firstWordLowerCase;

  public String getFirstWordLowerCase () {
    return firstWordLowerCase;
 }
}
</SSCCE>

Andrew T.
Tor Iver Wilhelmsen - 02 Jan 2007 15:57 GMT
>    sub.additionalFuntion(); //this method isn't available!
>                                       //why? I have a concrete
> refenence from type object_1,
>                                       //so why I can't call all
> object_1-functions???

Because there is a distinction between type-of-reference (which the
compiler uses to decide what members are visible) and type-of-objkect
(which the runtime uses to select the actual method invoked).

To call additionalFunction() you need to cast to object_1 first.
Lew - 02 Jan 2007 19:38 GMT
>>    sub.additionalFuntion(); //this method isn't available!
>>                                       //why? I have a concrete
[quoted text clipped - 7 lines]
>
> To call additionalFunction() you need to cast to object_1 first.

Besides that, it seems you need to rethink your inheritance hierarchy.

You haven't said much about your goal, but
> If I have 5 subclasses (object_1, object_2, .... , object_5) I can hold
> 5 object-references.
> But I don't want to do this....
> Is there any possibility, the realize it that way that I wanted it?
> (with one reference)

while hard for me to understand what you mean, seems to indicate that you
correlate types with object references, which is not a very precise view.

Inheritance models an "is-a" relationship, as in "Rectangle is-a Shape". Can
you say that your subclass represents a thing that "is a" member of the supertype?

Interfaces are raw types that define for all clients how a service class must
operate. They represent a behavioral contract. Can you say that all your
subclasses behave according to the interface contract?

Let us say that you have a class Foo with methodA() and methodB(). You want
some subclasses to implement a methodC(), belonging to interface Bar.

public class Foo
{
 public void methodA() { ... }
 public void methodB() ( ... }
}

public interface Bar
{
 void methodC();
}

public class FooSub extends Foo implements Bar
{
  public void methodC() { ... }
}

Now class FooSub "is a" Foo, and also FooSub "is a" Bar. FooSub has all three
methods.

public class TestFoos
{
 public static void main( String [] args )
 {
   FooSub sub = new FooSub();
   sub.methodA();
   sub.methodC();

   Foo foo = sub;
   foo.methodA();
//    foo.methodC(); // <== ILLEGAL! wrong compile-time type
   ((FooSub) foo).methodC(); // LEGAL if foo is rt type FooSub

   Bar bar = sub;
   bar.methodC();
//    bar.methodA(); // <== ILLEGAL! wrong compile-time type
   ((FooSub) bar).methodA(); // LEGAL if bar is rt type FooSub

 }
}

Note that in general downcasts like this are subject to ClassCastException
hurling if their run-time (rt) types don't match.

- Lew


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.