0

I'm new to Java and I'm trying to write a command line program that calculates section properties for various structural beams. The parent class Beam() has child classes Angle(), Tube(), and Rectangular(). I want the user to be able to create new beams and add the beams to a parent array like this:

Beam[] beams = new Beam[10];
Tube tb = new Tube(width, height, weight);
Angle ag = new Angle(width, height, flangeWidth);

Ideally I'd like to do something like this but I can't because the objects are different types.

beams.add(tb);
beams.add(ag);

How can I work around this to keep track of the child objects? I'd like to print all objects in the array and give the user the choice to select an object and print out calculated values for it.

4
  • If you are using Arrays, should you do something like beams[0] = tb; beams[1] = ag? Commented Jun 5, 2021 at 1:21
  • The class names are throwing me off. Either Angular/Angled, Tubular, Rectangular, or Angle, Tube, Rectangle would be more consistent. Commented Jun 5, 2021 at 1:23
  • 2
    I think you need to keep reading the tutorial Commented Jun 5, 2021 at 1:24
  • Good point about the class names; I'll definitely change them to make them more consistent. Thanks for the comment. I'm in a Java 101 class so I am still learning. Commented Jun 5, 2021 at 2:09

2 Answers 2

2

Arrays have no add method. You must assign content objects into specific element slots.

Beam[] beams = new Beam[10];
beams[0] = new Tube(width, height, weight);
beams[1] = new Angle(width, height, flangeWidth);

More conveniently, use a List such as ArrayList rather than a mere array.

List< Beam > beams = new ArrayList <> ( 10 ) ;
beams.add( new Tube(width, height, weight) ) ;
beams.add( new Angle(width, height, flangeWidth) ) ;

As commented, this is basic Java 101 stuff. You should spend more time studying the basics, such as the free tutorial online by Oracle, or the excellent though somewhat outdated book, Head First Java by Kathy Sierra, et al.

Sign up to request clarification or add additional context in comments.

Comments

0

I think it's better to use a dynamic array for your work. Do not use Arrays use ArrayList class in collection API.

ArrayList< Beam > beams = new ArrayList <>;
beams.add( new Tube(width, height, weight) ) ;
beams.add( new Angle(width, height, flangeWidth) ) ;

As you are new to java please go through the collection API it will help you to use proper data structures when you coding.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.