Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

AuntJemima

macrumors newbie
Original poster
Jan 14, 2008
15
0
Sorry I m studying java and alittle new to the language but have a question about inheritance....

if I have a bunch of classes and each on extends the next and I add an overrided method to the 'class2' after the 'class1', will the method from 'class1' that has been override by the 'class2' be forgotten because it has been overridden or what?

I know this happens with constructors but what about my situation?

Thanks
jgwc
 
It's not "forgotten" but the overriding method will be called. You can still use super.methodName from class2 to call the method in class1...
 
but if I don't call it(i.e. super.methodName) than it won't be automatically included in the extended class('class2')?
 
But what happens if you... (aside from the fact that this probably won't compile but hopefully you get the drift...)

Code:
class MyClassA {
    public void myMethod() {
        System.out.println("Class A");
    }
}

class MyClassB extends MyClassA {
    public void myMethod() {
        System.out.println("Class B");
    }    
}

MyClassA myObject = new MyClassB();
myObject.myMethod();

Does it print "Class A" or "Class B"? I've been reading too much (or perhaps not enough if the code is bad enough) of my Java Cert book...
 
OP, what are you using to study Java?


I don't know if you were referring the question to me but I am using a book called 'Beginning Java Objects From Concepts to Code'

Is that what you were looking for?
 
But what happens if you... (aside from the fact that this probably won't compile but hopefully you get the drift...)
...
Does it print "Class A" or "Class B"? I've been reading too much (or perhaps not enough if the code is bad enough) of my Java Cert book...

Should be "Class B", while the reference (containter) is pointing to A, the actual object your are invoking the method on is an instance of B.

Are you studying to get a SCJP cert?

I don't know if you were referring the question to me but I am using a book called 'Beginning Java Objects From Concepts to Code'

Is that what you were looking for?
yeah you :) Take a look at Head First Java, I think it is a must to learn the language. Oh, and it is a blast to use too.
 
Should be "Class B", while the reference (containter) is pointing to A, the actual object your are invoking the method on is an instance of B.

Are you studying to get a SCJP cert?

Yeah. I was mostly posing it to the forum as I had recently read the answer. I've been doing Java coding for seemingly ever so most of the book is just a rehash of things I already do day to day.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.