Results 1 to 2 of 2
- 11-21-2012, 02:08 AM #1
Member
- Join Date
- Oct 2012
- Posts
- 7
- Rep Power
- 0
this(), and super() within a method (not a constructor)
This has been giving me a brain aneurysm. Help!
Two Classes:
Java Code:class Feline { public String type = "f "; public Feline() { System.out.print("feline "); } }The result of the execution of the Cougar class results in: feline cougar c cJava Code:public class Cougar extends Feline { public Cougar() { System.out.print("cougar "); } public static void main(String[] args) { new Cougar().go(); } void go() { type = "c "; System.out.print(this.type + super.type); } }
I had thought that it would be c f since super() was used and that would call the parent class. But then I remembered that I had learned that super() deals with constructors..so:
What is the purpose of the super() within the go() method? I thought that super() was only to be used and referred within constructors to refer to the parent constructor. If that's the case why doesn't the above code give an error?
- 11-21-2012, 03:31 AM #2
Senior Member
- Join Date
- Jun 2007
- Location
- Bali, Indonesia
- Posts
- 696
- Rep Power
- 6
Re: this(), and super() within a method (not a constructor)
Hi,
When you create an instance of Cougar class the Feline constructor will be called because the Cougar class extends the Feline class. That's why you program print out "feline" which is printed at the Feline constructor. The "cougar" is printed by the Cougar constructor when you create an instance of Cougar.
In the go() method you set the public variable named type value to "c". Because it is public it will change also the value in the Feline class. That why when you print the type variable it show "c c".
super keyword can be use not only in the constructor. it is use to call what the parent class have. for example if you define a go() method in the Feline class you can call it using super.go() so that it will call the parent class method instead of the go() method in the Cougar class.Website: Learn Java by Examples
Similar Threads
-
Java - Constructor Method versus Constructor
By brocksoffice in forum New To JavaReplies: 1Last Post: 08-01-2012, 09:17 AM -
What, if we call super() from parents default constructor?
By ezee in forum New To JavaReplies: 3Last Post: 11-01-2011, 08:24 AM -
Whats the different between package.class.method and super.method?
By Pojahn_M in forum New To JavaReplies: 1Last Post: 10-17-2011, 01:00 AM -
Junit3 error: Implicit super constructor TestCase() is not visible
By albertkao in forum Advanced JavaReplies: 3Last Post: 01-21-2011, 01:37 PM -
Private constructor and super()
By Basit56 in forum Advanced JavaReplies: 9Last Post: 08-21-2009, 06:19 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks