Results 1 to 2 of 2
  1. #1
    milleniamisc is offline Member
    Join Date
    Oct 2012
    Rep Power

    Default 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 ");
    Java 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);
    The result of the execution of the Cougar class results in: feline cougar c c

    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

    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?

  2. #2
    wsaryada is offline Senior Member
    Join Date
    Jun 2007
    Bali, Indonesia
    Rep Power

    Default Re: this(), and super() within a method (not a constructor)


    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.

Similar Threads

  1. Java - Constructor Method versus Constructor
    By brocksoffice in forum New To Java
    Replies: 1
    Last Post: 08-01-2012, 09:17 AM
  2. Replies: 3
    Last Post: 11-01-2011, 08:24 AM
  3. Replies: 1
    Last Post: 10-17-2011, 01:00 AM
  4. Replies: 3
    Last Post: 01-21-2011, 01:37 PM
  5. Private constructor and super()
    By Basit56 in forum Advanced Java
    Replies: 9
    Last Post: 08-21-2009, 06:19 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts