[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 218
  • Last Modified:

Return Types

Hi

i have devised a solution to access a superclass arraylist by returning an arraylist of the current arraylist in the superclass.

Is this god programming, is it allowed, is there any other solutions to access the arraylist from the subclass, withought having a protected field.

This is what i was going to use:

public abstract class A
{
    private ArrayList list1;

    public ArrayList method1()
    {
         return list1;
     }
}

my subclass uses method1 from superclass to access the arraylist from the superclass A and print the contents from it:

public class B extends A
{
    public void printlist1()
    {
        Iterator it = method1().iterator();
        while(it.hasNext())
         {
            system.out.println(it.next());
          }
    }
}

Any help on this subject would be great
Thanks alot
0
Case-Sensitive
Asked:
Case-Sensitive
  • 2
  • 2
2 Solutions
 
petmagdyCommented:
Hi Case-Sensitive,

the returned from method is the reference to the object holded by the supperclass so u can read & modify its contents, so yes u can do that

Cheers!
0
 
Case-SensitiveAuthor Commented:
Hey thanks alot

I was wondering if it is a good idea to inherit an ArrayList from an abstract class, it seems to make the job alot harder when adding to or retreiving from the subclasses.

Should i use an individual ArrayList inside class B or Class C and remove it from class A?

any help on this
Cheers!
0
 
suprapto45Commented:
Hi,

Basically it depends on your needs. Consider this, you will only inherit if your Class A and Class B are having the common characteristics. So in your case, you should inherit the ArrayList list1 if your class B should have the ArrayList list1 too (then you do not need to define it anymore). In simpler example, Animal has legs and so does Dogs thus class Dogs will *extends* class Animal and automatically get the inherited legs :). However, if you do not find that class B should not have the list1 as the field, you can just call the class A and not extends class A.

I hope that helps.

Regards
Dave

0
 
suprapto45Commented:
Hi,

remember that only extends one class only if you really need it. One java class can only extends one class and no more.

Regards
Dave
0
 
petmagdyCommented:
Case-Sensitive,

I say keep it in the base class, it is always a Good OOP practice to keep the common attributes (member fields) in the base class
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now