How to best use these slides View the
How to best use these slides… • View the PPT as a slide show • Then click through every step • Mouse clicks will advance the slide show • Left/right arrow keys move forward/backward • Mouse wheel scrolling moves forward/backward • When a question is posed, stop and think it through, try to answer it yourself before clicking • If you have questions, use PS discussion boards, email me, and/or visit us in a Teams class session! Copyright 2008 by Pearson Education 1
A Short but Deep Dive into Constructors A constructor is what is used to create and initialize an object (an instance of a class) It looks like a method… • BUT IT IS NOT A METHOD! You can tell it is a constructor (looking at the code for the class): • has the same name as the class • does NOT have a return type • is (almost) always public A default constructor is a constructor that takes no arguments Copyright 2008 by Pearson Education 2
Not a method? What does that mean? The main reason constructors are not methods is: • constructors are NOT inherited even if they are public • methods ARE inherited as long as they are not private Okay, so what? The fact that constructors are not inherited has one SUPER SIGNIFICANT impact: • If you write a constructor for a subclass, the first line MUST be a call to a superclass constructor • To call the constructor from the superclass, use the keyword super: Copyright 2008 by Pearson Education 3
Why does my subclass constructor have to call the superclass constructor 1 st? Think of this from a venn diagram perspective: • • • The subclass encapsulates the superclass • The superclass is part of the subclass • The superclass is a smaller bubble inside the subclass The subclass extends the superclass • The subclass “is-a” same thing as the superclass • The subclass “adds to” the superclass subclass superclass If you are going to initialize and setup an instance of the subclass • You also have initialize and setup the superclass part of it • It makes sense you want to work from the inside out… • …initialize your core, then initialize the rest. • The superclass is the “core” of the subclass Copyright 2008 by Pearson Education 4
QUICK SUMMARY Constructors are NOT methods • a subclass does not inherit the constructors from the superclass If you extend a superclass and write your own constructors • the 1 st line of each constructor MUST call a constructor from the superclass Copyright 2008 by Pearson Education 5
- Slides: 5