Page 1 of 2 12 LastLast
Results 1 to 20 of 24
  1. #1
    Claymz is offline Member
    Join Date
    Apr 2011
    Posts
    25
    Rep Power
    0

    Default Accessing abstract class subclass's data members

    Hi,

    I think the title says it all but anyway...

    I have this abstract class, and i want to access one subclass's data member, which his parent abstract class does not contain. I want to acces it from another class, which takes as parameters objects of this abstract class.

    Any help would be appreciated :).

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

    Default

    You can cast the parameter to the subclass so that members and methods of the subclass can be called. But...

    A method's parameters ought to reflect the type of thing that the method expects to be called with. So if the method is going to access things which are proper to the subclass then the parameter ought to express that fact and have the type of the subclass.

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

    Default

    In code:

    Java Code:
    class Foo {}
    class Bar extends Foo {
        public void whatever() {}
    }
    class Other {
        public void nasty(Foo foo) {
            Bar bar = (Bar)foo;
            bar.whatever();
        }
        public void nice(Bar bar) {
            bar.whatever();
        }
    }

    Consider the case where Foo is Object and ask yourself why we *ever* use parameters of any other type.

  4. #4
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,784
    Rep Power
    7

    Default

    Extending the above example to highlight a very nasty situation.
    Java Code:
    class Widget extends Foo {
        public void noWhateverMethod() {}
    
        public static void main(String[] args) {
            Other oth = new Other();
            Widget w = new Widget();
            oth.nasty(w); // KABOOM!
        }
    }

  5. #5
    Claymz is offline Member
    Join Date
    Apr 2011
    Posts
    25
    Rep Power
    0

    Default

    tnx for the fast reply...

    but what i actually need now is this:

    im working with Linked list, and im having problem with declaring constructor in my list linked class, specifically:

    Java Code:
    	public List() {
    		first = new ListLinkedNode(null);
    		last = first;
    	}
    the problem is, as stated before, that im using abstract class for ListLinkedNode, so i cant instantiate it, but for Linked list to work, i have to... So, what to do?

  6. #6
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,784
    Rep Power
    7

    Default

    Why is ListLinkedNode abstract? If it is abstract you cannot create an instance of it.

  7. #7
    Claymz is offline Member
    Join Date
    Apr 2011
    Posts
    25
    Rep Power
    0

    Default

    thats the assignment :( so is there no other way?

  8. #8
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,784
    Rep Power
    7

    Default

    How about explaining what you need to do, not how you are trying to do it.

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

    Default

    How about explaining what you need to do

    In other words what does the assignment question actally ask? Don't worry, nobody is going to rob you of the fun of actually answering the question yourself.

  10. #10
    Claymz is offline Member
    Join Date
    Apr 2011
    Posts
    25
    Rep Power
    0

    Default

    well, i have this class called Train, which in one of its methods takes object of abstract class called Element as parameter. Classes Wagon and Locomotive extends Element class. Im using Train as list of elements, and Element as one of the element of this list. So i need to make an instance of this Element class, but i cant. I guess i need a different approach, but Train needs to take Element object's as parameter in one of the methods...

    Java Code:
    abstract class Element
    {
    	Double maxMass;
    	Element next;
    	
    	public Element(Double maxMass) 
    	{
    		this.maxMass = maxMass;
    		next = null;
    	}	
    }
    
    class Locomotive extends Element 
    {	
    	public Locomotive(double maxMass) 
    	{
    		super(maxMass);
    	}
    }
    
    class Wagon extends Element 
    {
    	private double massCurrentCargo;
    	
    	public Wagon(double maxMass)
    	{
    		super(maxMass);
    		massCurrentCargo= 0;
    	}
    }
    class Train  
    {	
    	private Element first, last;
    	
    	public Train()
    	{
    		first = new Element(null); // The conflict line!
    		last = first;
    				
    	}
    
    	public boolean add(Element el) 
    	{		
    		if(el.getClass().getName() == "Locomotive")   
    		{	
    			if(first.next.getClass().getName() != "Locomotive")
    			{
    				first.next = el;   // The first element
    				last = first.next; // When only one element is in the 
                                                           // list, it is also the last one - is 
                                                           // this true? (in sense of Linked list)
                            }
    		}
    		
    		else if(el.getClass().getName() == "Wagon")
    		{			
    			last.next = el;
    			last = el;
    		}
    
    		return true;
    	}
    
            //other methods...
    }

  11. #11
    Claymz is offline Member
    Join Date
    Apr 2011
    Posts
    25
    Rep Power
    0

    Default

    ok, i figured i need another class, which represents the element of the list, but in my case the class Element took that role also, so that was the problem...

  12. #12
    snotmare is offline Member
    Join Date
    Apr 2011
    Posts
    34
    Rep Power
    0

    Default

    As mentioned above, you can't instantiate an abstract class. If you need to default your first element to something, you might consider creating an instance of locomotive. Or, you need to leave first as null, and deal with it later.

    You can use instanceof to determine what class it is, but there is a very important difference between isntanceof and getClass().getName() == "foo".

    Using your example, say you have the following...

    Java Code:
    static public void myTest(){
    	Element element = new Locomotive(0);
    	Locomotive locomotive = new Locomotive(0);
    	
    	System.out.println(element instaceof Element);
    	System.out.println(element instaceof Locomotive);
    	System.out.println(locomotive instaceof Element);
    	System.out.println(locomotive instaceof Locomotive);
    	System.out.println(element.getClass().getName() == "Element");
    	System.out.println(element.getClass().getName() == "Locomotive");
    	System.out.println(locomotive.getClass().getName() == "Element");
    	System.out.println(locomotive.getClass().getName() == "Locomotive");
    }
    Your output would be:
    true
    true
    true
    true
    false
    true
    false
    true

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

    Default

    Avoid "instanceof". And don't compare strings (or any other objects) with ==. CLasses provide an equals() method for testing for equality.

    -----------------

    You haven't really said exactly what the assignment asked. But in general the fact that Train has a method that takes an Element parameter is not a reason for having to construct instances of Element directly.

    For example if Train has an add method taking a an Element parameter then you can call this method with a Locomotive instance or a Wagon instance. The reason you can do this is is that a Locomotive IS-AN Element and a Wagon IS-AN element.

    Things only get messy if the add() method is required to do different things depending on the specific type of the thing being added. (Real trains, eg, don't have this requirement and can be shunted as well as pulled. They can have multiple locomotives etc So it doesn't matter how many or where the locomotives are added.) Only in such a case would you have to resort to "instanceof" with all its ugliness. I wouldn't suggest that unless the assignment specifically required it.

  14. #14
    snotmare is offline Member
    Join Date
    Apr 2011
    Posts
    34
    Rep Power
    0

    Default

    @ pbrockway2

    I generally agree that using == to compare 2 objects is not the right way, since it tests identity, not equality. However, since a String is immutable and String overwrote the equals and hashCode correctly, == works perfectly fine. I suppose an even better way is to use apache's StringUtils.equals(String, String) method! :)

    Also, I'm not sure why you'd want to avoid instanceof if it's necessary. Generics make it less needed, but there are still some cases where you need to know what type of Object it is. If you were to avoid instanceof, what would be a better alternative?

  15. #15
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,784
    Rep Power
    7

    Default

    Quote Originally Posted by snotmare View Post
    I generally agree that using == to compare 2 objects is not the right way, since it tests identity, not equality. However, since a String is immutable and String overwrote the equals and hashCode correctly, == works perfectly fine.
    Incorrect.
    Java Code:
    String s1 = "hello";
    String s2 = new String(s1);
    String s3 = new String("hello");
    System.out.println(s1 == s2);
    System.out.println(s1 == s3);
    Output is false and false.

  16. #16
    Claymz is offline Member
    Join Date
    Apr 2011
    Posts
    25
    Rep Power
    0

    Default

    I answered my question mysely already, as i mentioned in my previous post! :) But thanks very much for all other information about it anyway!

    I have another one though: how do i access parent class's private data members(which are, obviously, inherited by this class itself)?

  17. #17
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Claymz View Post
    I have another one though: how do i access parent class's private data members(which are, obviously, inherited by this class itself)?
    You don't.

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

    Default

    Also, I'm not sure why you'd want to avoid instanceof if it's necessary.

    And I'm quite sure I wouldn't want to avoid anything that's necessary. But it was the necessity that I was questioning.

  19. #19
    snotmare is offline Member
    Join Date
    Apr 2011
    Posts
    34
    Rep Power
    0

    Default

    @ Junky
    You are correct, however, I am also correct. This is what I was referring to...

    Java Code:
    String test1 = "test";
    String test2 = "test";
    
    System.out.println(test1 == test2);
    The output for this is true. As was mentioned, the better way to test Strings is by the .equals method, or Apache's StringUtils. I never code == for Strings for the reasons you posted.

  20. #20
    Claymz is offline Member
    Join Date
    Apr 2011
    Posts
    25
    Rep Power
    0

    Default

    Ok, ive stunned upon another obsticle:

    I want to access private data members of class Train, from class Wagon (of which instances Train takes). So i made a private data member of Train in Wagon (private Train train;), and when i add a Wagon object to the Trains one, i have this assignment: vagon = (Vagon)el; (just for type conversion so i can be able to access Wagons "train" data member, because its inhereted class) and then: vagon.vlak = this;. With that in place, i would want to access Trains data members in Wagon class with its accessor methods (vlak.getSomemethod()), but i still get the null pointer exception. Any ideas?

Page 1 of 2 12 LastLast

Similar Threads

  1. Sharing Data Members between two JFrames
    By PrinceSendai in forum AWT / Swing
    Replies: 3
    Last Post: 10-17-2010, 02:51 AM
  2. private data members?
    By blueduiker in forum New To Java
    Replies: 10
    Last Post: 01-19-2010, 11:13 AM
  3. [newbie] getting class members from Arraylist
    By jon80 in forum New To Java
    Replies: 16
    Last Post: 05-15-2009, 07:45 AM
  4. Replies: 6
    Last Post: 02-11-2009, 10:51 AM
  5. Doclet that prints out all members of the class
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-16-2008, 11:06 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
  •