Results 1 to 13 of 13
  1. #1
    Robben is offline Member
    Join Date
    Feb 2015
    Posts
    67
    Rep Power
    0

    Default Super class and sub class

    I am a bit confused on how to go about doing this.

    Suppose I have a super class named Super and a subclass of Super class named Sub. Now, I have two instance variables (that has value string named firstName and lastName) marked as protected under Super class and I made getters for them, lets call them, getFirstName(). I also created a constructor, Super(firstName, lastName) that has two parameters, i.e. it has the parameters of the instance variable string. Now under my Sub class I have a system.out.println(getFirstName()). So to test this I made a main method and created an object for the Super class, i.e Super s = new Super("Robben", "Tale") and I also made an object for the Sub class so that it will print out the firstName. But it prints out null? Why is that? If a subclass inherits all the variables and methods from the super class shouldn't it print out Robben instead of null?

    Java Code:
    public class Super {
        protected String firstName;
        protected String lastName;
    
        public Super(String firstName, String lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }
    
        public String getFirstName() {
            return firstName;
        }
    }
    
    ------ different file ---------
    
    public class Sub extends Super {
        public Sub(int x) {
            System.out.println(getFirstName());
        }
    }
    
    ---- new file where the main is --------------
    
    public class OurMain {
    	public static void main(String[] args) {
                Super x = new Super("Robben", "Tale")
                Sub x = new Sub(5);

    Sub x = new Sub(5) prints out null instead of Robben why is that? My hierarchy must not be correct.

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,716
    Rep Power
    18

    Default Re: Super class and sub class

    Does your code compile? I'm wondering because you can't declare a variable twice as you do x in main(). And the Sub() constructor must (explicitly or implicitly) call a Super() constructor.

    Apart from all this your main method assigns to x references to two different and totally unrelated objects. (In general "new" gives you something ... new.) So there's no way we can expect "new Sub(5)" to print "Robben".

  3. #3
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Super class and sub class

    When you do Sub x = new Sub(5), you are creating a whole new instance. Instance fields are not shared across different objects of the same class or hierarchy.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  4. #4
    Robben is offline Member
    Join Date
    Feb 2015
    Posts
    67
    Rep Power
    0

    Default Re: Super class and sub class

    Quote Originally Posted by pbrockway2 View Post
    Does your code compile? I'm wondering because you can't declare a variable twice as you do x in main(). And the Sub() constructor must (explicitly or implicitly) call a Super() constructor.

    Apart from all this your main method assigns to x references to two different and totally unrelated objects. (In general "new" gives you something ... new.) So there's no way we can expect "new Sub(5)" to print "Robben".
    That was a mistake on my part, it the second x should be x1.


    Java Code:
    When you do Sub x = new Sub(5), you are creating a whole new instance. Instance fields are not shared across different objects of the same class or hierarchy.
    
    Regards,
    Jim
    But then how can I make it print "Robben"?

  5. #5
    Robben is offline Member
    Join Date
    Feb 2015
    Posts
    67
    Rep Power
    0

    Default Re: Super class and sub class

    Quote Originally Posted by pbrockway2 View Post
    Does your code compile? I'm wondering because you can't declare a variable twice as you do x in main(). And the Sub() constructor must (explicitly or implicitly) call a Super() constructor.

    Apart from all this your main method assigns to x references to two different and totally unrelated objects. (In general "new" gives you something ... new.) So there's no way we can expect "new Sub(5)" to print "Robben".
    That was a mistake on my part, the second x should be x1.


    When you do Sub x = new Sub(5), you are creating a whole new instance. Instance fields are not shared across different objects of the same class or hierarchy.

    Regards,
    Jim
    But then how can I test my code to see if it prints "Robben"?
    Last edited by Robben; 02-28-2015 at 01:31 AM.

  6. #6
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Super class and sub class

    Quote Originally Posted by Robben View Post
    But then how can I test my code to see if it prints "Robben"?

    Java Code:
    Super x = new Super("Robben", "Tale");
    System.out.println(x.getFirstName());
    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  7. #7
    Robben is offline Member
    Join Date
    Feb 2015
    Posts
    67
    Rep Power
    0

    Default Re: Super class and sub class

    Quote Originally Posted by jim829 View Post
    Java Code:
    Super x = new Super("Robben", "Tale");
    System.out.println(x.getFirstName());
    Regards,
    Jim
    Hm, but I want to test if it prints out in the Sub class. Because in my sub class I want to add some helper methods that changes the firstName. If it only prints out while I am in the Super class then my Sub class is pretty useless.

  8. #8
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Super class and sub class

    Then create the instance using Sub. But you need to modify your constructors for Sub.

    Java Code:
    class Sub extends Super {
       public Sub(String first, String last) {
          super(first, last);
       }
    }
    Then in your test class

    Java Code:
    Sub x = new Sub("Robben", "Tale");
    System.out.println(x.getFirstName();
    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  9. #9
    Robben is offline Member
    Join Date
    Feb 2015
    Posts
    67
    Rep Power
    0

    Default Re: Super class and sub class

    Quote Originally Posted by jim829 View Post
    Then create the instance using Sub. But you need to modify your constructors for Sub.

    Java Code:
    class Sub extends Super {
       public Sub(String first, String last) {
          super(first, last);
       }
    }
    Then in your test class

    Java Code:
    Sub x = new Sub("Robben", "Tale");
    System.out.println(x.getFirstName();
    Regards,
    Jim
    But then that will make my Super class pretty useless to have. Is there no way other way to print out the parameters that was passed in the Super class when I am in the Sub class?
    I want my Sub class to printout whats passed in the Super class.

  10. #10
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Super class and sub class

    You can't create an instance of Super with constructor values and then a separate instance of Sub and expect it to know about those values. Those are two different instances and thus the instance fields contain different values. If you can explain what your ultimate goal is perhaps I or someone on this forum could steer you in the right direction. It might be useful to review inheritance. Check out the Java tutorials in my signature.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  11. #11
    Robben is offline Member
    Join Date
    Feb 2015
    Posts
    67
    Rep Power
    0

    Default Re: Super class and sub class

    Quote Originally Posted by jim829 View Post
    You can't create an instance of Super with constructor values and then a separate instance of Sub and expect it to know about those values. Those are two different instances and thus the instance fields contain different values. If you can explain what your ultimate goal is perhaps I or someone on this forum could steer you in the right direction. It might be useful to review inheritance. Check out the Java tutorials in my signature.

    Regards,
    Jim
    Will do thank you!

    My goal is to make a Super class and a Sub class.

    The Super class has the property that inputs people's name and checks if two people are alike, hence the constructor of the firstName and lastName. This class also compares itself to other members of the Super class. My super class is the following:

    Java Code:
    public class Person implements Comparable {
        protected String firstName;
        protected String lastName;
        protected int age;
    
        public Person() {
        	this(0,null,null);
        }
    
        public Person(int age, String lastName, String firstName) {
    		this.age = age;		
    		this.lastName = lastName;
    		this.firstName = firstName;
    	}
    
    	public String getFirstName() {
    		return firstName;
    	}
    
    	public String getLastName() {
    		return lastName;
    	}
    
    	public int getAge() {
    		return age;
    	}
    
    	
        
        public int compareTo(Object temp) {
        	Person other = (Person) temp;
    
        	if (getAge() > other.getAge()) {
        		return 1;
        	} else if (getAge() < other.getAge()) {
        		return -1;
        	} else if (getLastName().compareTo(other.getLastName())>0) {
        		return 1;
        	} else if (getLastName().compareTo(other.getLastName())<0) {
        		return -1;
        	} else if (getFirstName().compareTo(other.getFirstName())>0) {
        		return 1;
        	} else if (getFirstName().compareTo(other.getFirstName())<0) {
        		return -1; 
        	} else {return 0;}
        }
    
        public boolean equals(Person other) {
    
        	if (other != null) {
        		if (other.age == this.age && other.lastName == this.lastName && other.firstName == this.firstName) {
        			System.out.println("These people are equal");
        			return true;
        		}    	
        	} 
        	System.out.println("These people are different");
        	return false;
        }
    
    	public String toString() {
    		return "Age: " + getAge() + ", LastName: " + getLastName() + ", FirstName: " + getFirstName();
    	}
    
    
    }
    My sub class should create a new identity of the person by changing the first and last names (it doesn't really matter what their names are changed into but they must be changed into anything that is different from the original names).

  12. #12
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,716
    Rep Power
    18

    Default Re: Super class and sub class

    Did you understand my observation that "the Sub() constructor must (explicitly or implicitly) call a Super() constructor"?

    The point is that any instance of the subclass really is an instance of the superclass as well. Consequently the super class constructor does have to be called, as Jim illustrated in #8.

    ---

    If you really want to a person instance to change their name, then use a setter method. There is no need for a subclass to be involved. IRL people (and not subclassed in any way) do this by deed poll.

    On the other hand if you want an instance of Person to have another property like "aka" there might be a case for having a subclass (although I'm not convinced). Suppose the subclass of Person is AliasedPerson. The fact that an AliasedPerson is also a Person means that an aliased person also has a first name and a last name, and the AliasedPerson constrcutor will ensure somehow that these fields are set.

    Spelling out Jim's example a little:

    Java Code:
    class AliasedPerson extends Person {
       protected String aka;
       public Person(String first, String last, String aka) {
          super(first, last);
          this.aka = aka;
       }
    }
    
    // then, later...
    AliasedPerson x = new AliasedPerson("Robben", "Tale", "Coder");
    System.out.println(x.getFirstName();
    It should be noted that when you say "new Whatever()" you create a reference to a new instance of a particular type. The type simply cannot change later. (Think leopard and spots, not Javascript.) If a Person is an AliasedPerson (with an aka) then they were created as a new AliasedPerson(...), they cannot begin life as a Person instance and acquire the aka later. (Partly that's why I'm not so sure having a name changed person as a subclass of person is a good design.)
    Last edited by pbrockway2; 02-28-2015 at 05:20 AM.

  13. #13
    Robben is offline Member
    Join Date
    Feb 2015
    Posts
    67
    Rep Power
    0

    Default Re: Super class and sub class

    Quote Originally Posted by pbrockway2 View Post
    Did you understand my observation that "the Sub() constructor must (explicitly or implicitly) call a Super() constructor"?

    The point is that any instance of the subclass really is an instance of the superclass as well. Consequently the super class constructor does have to be called, as Jim illustrated in #8.

    ---

    If you really want to a person instance to change their name, then use a setter method. There is no need for a subclass to be involved. IRL people (and not subclassed in any way) do this by deed poll.

    On the other hand if you want an instance of Person to have another property like "aka" there might be a case for having a subclass (although I'm not convinced). Suppose the subclass of Person is AliasedPerson. The fact that an AliasedPerson is also a Person means that an aliased person also has a first name and a last name, and the AliasedPerson constrcutor will ensure somehow that these fields are set.

    Spelling out Jim's example a little:

    Java Code:
    class AliasedPerson extends Person {
       protected String aka;
       public Person(String first, String last, String aka) {
          super(first, last);
          this.aka = aka;
       }
    }
    
    // then, later...
    AliasedPerson x = new AliasedPerson("Robben", "Tale", "Coder");
    System.out.println(x.getFirstName();
    It should be noted that when you say "new Whatever()" you create a reference to a new instance of a particular type. The type simply cannot change later. (Think leopard and spots, not Javascript.) If a Person is an AliasedPerson (with an aka) then they were created as a new AliasedPerson(...), they cannot begin life as a Person instance and acquire the aka later. (Partly that's why I'm not so sure having a name changed person as a subclass of person is a good design.)
    I see, thank you very much to both of you! I will rewrite my code with both of your suggestions. Thanks again!

Similar Threads

  1. Super class, Sub class, and Abstract classes
    By csanch11 in forum New To Java
    Replies: 1
    Last Post: 11-22-2014, 08:09 AM
  2. Replies: 1
    Last Post: 05-08-2012, 09:40 PM
  3. Replies: 2
    Last Post: 08-17-2011, 08:09 AM
  4. Replies: 5
    Last Post: 01-26-2011, 06:38 PM
  5. Class Reflection: Finding super class names
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-23-2008, 08:12 PM

Posting Permissions

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