Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Subclasses in Superclass array

  1. #1
    Junior Member
    Join Date
    Oct 2020
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Subclasses in Superclass array

    I have a superclass (Student) and two subclasses (RStudent and CStudent) that inherit from Student. I want to be able to have one ArrayList of both RStudent and CStudent. I tried just using ArrayList<Student> students = new Arraylist<>(); but I cant access any variables that are specific to the subclasses. For example if I use students.add(newCStudent), when I try use students.get(0).mark (which is a variable only in CStudent) it doesn't work. How can I do this?

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Subclasses in Superclass array

    it doesn't work. How can I do this
    Cast the value from the List to the subclass it is to make its contents available.

    Why are the subclasses mixed together in the List if you want to treat them as subclasses instead of strictly accessing them with superclass methods?
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Replies: 0
    Last Post: July 19th, 2012, 09:02 AM
  2. Replies: 2
    Last Post: March 15th, 2012, 08:25 PM
  3. Overriding Superclass Static Methods, Using the Superclass Method
    By snowguy13 in forum Java Theory & Questions
    Replies: 10
    Last Post: December 21st, 2011, 08:30 AM
  4. Using an array which is in a superclass
    By razorfever in forum Object Oriented Programming
    Replies: 2
    Last Post: October 29th, 2011, 12:05 PM
  5. EXAMPLE OF FILTERSTREAMS SUBCLASSES.
    By ordonezc78 in forum File I/O & Other I/O Streams
    Replies: 0
    Last Post: March 22nd, 2011, 11:38 PM

Tags for this Thread