Results 1 to 3 of 3
- 02-08-2013, 07:42 PM #1
Senior Member
- Join Date
- Dec 2007
- Location
- Spain
- Posts
- 1,139
- Rep Power
- 13
A small question concerning super
A small question concerning super
Here is a code sample from the Think in Java book
why is sup.getField one and not zero (see code all the way down)
It probably boils down to the difference of
Super s = new Sub();
Super s = new Super();
right?
Java Code://: polymorphism/FieldAccess.java // Direct field access is determined at compile time. class Super { public int field = 0; public int getField() { return field; } } class Sub extends Super { public int field = 1; public int getField() { return field; } public int getSuperField() { return super.field; } } public class FieldAccess { public static void main(String[] args) { Super sup = new Sub(); // Upcast System.out.println("sup.field = " + sup.field + ", sup.getField() = " + sup.getField()); Sub sub = new Sub(); System.out.println("sub.field = " + sub.field + ", sub.getField() = " + sub.getField() + ", sub.getSuperField() = " + sub.getSuperField()); } } /* Output: sup.field = 0, sup.getField() = 1 sub.field = 1, sub.getField() = 1, sub.getSuperField() = 0 *///:~
Last edited by willemjav; 02-08-2013 at 07:44 PM.
- 02-08-2013, 08:55 PM #2
Re: A small question concerning super
Why do you think it should be 0?
The instance is of Sub type. The Sub getField() method returns the field value of the Sub class. That value is 1.How to Ask Questions the Smart Way
Static Void Games - GameDev tutorials, free Java and JavaScript hosting!
Static Void Games forum - Come say hello!
- 02-08-2013, 10:43 PM #3
Senior Member
- Join Date
- Dec 2007
- Location
- Spain
- Posts
- 1,139
- Rep Power
- 13
Similar Threads
-
I am a super noob with a super noob question.
By LittleZoppo in forum Java AppletsReplies: 3Last Post: 04-27-2012, 04:50 AM -
Please help,just a small question
By JavaDreams in forum New To JavaReplies: 5Last Post: 01-28-2011, 09:15 PM -
small question about 'this'
By GPB in forum New To JavaReplies: 3Last Post: 02-28-2010, 06:46 PM -
Super simple question
By jigglywiggly in forum New To JavaReplies: 3Last Post: 01-26-2009, 02:17 AM -
A small Question
By Eku in forum JDBCReplies: 7Last Post: 09-01-2008, 07:10 AM
Bookmarks