Inheritance - Introduduction to Jave Programming - Lecture Slides, Slides of Java Programming

In the course of the Introduction to Jave Programming, we study the basic syntax and the basic program in java. In these lecture slides the key points are: Inheritance, Extending Classes, Super Keyword, Story Time, Extending Classes, Parent Class, Arrakiansandworm, Private Means, Private Data, Methods Are Needed

Typology: Slides

2012/2013

Uploaded on 04/23/2013

sarmistha
sarmistha 🇮🇳

3.8

(22)

112 documents

1 / 18

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Inheritance
Docsity.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12

Partial preview of the text

Download Inheritance - Introduduction to Jave Programming - Lecture Slides and more Slides Java Programming in PDF only on Docsity!

Inheritance

Highlights

  • Extending classes (inheritance)
  • super keyword

Story time

Story time

Extending classes

(See: DuneCat.java and ArrakianSandworm.java) Extended (child) classes get objects and methods from their parent class For example, DuneCat (child) got the roar() method from ArrakianSandworm (parent) (not possible to extend from 2 classes)

What do child classes get?

Child classes get all objects and (public) methods from the parent class Remember: private means they can only be used inside the class where it is defined To access and modify private data, public methods are needed (get___() and set___()) (See: Parent.java and Child.java)

AD&D example

Using child and parent classes

You can think of a child class as a more specific instance of a parent class This means you can think of a child object as type parent (but not parent as type child) (See: UsingInheritance.java)

Oddities of super() constructor

If you do not code super() on the first line of a child class's constructor, then... ● The parent's default constructor will run ● If the parent does not have a default constructor, there will be an error This is a reason why it is normally useful to have a default constructor defined, even if it does nothing

this

We introduced this a while back, but you can also use this to run constructors (like super) If you use this as a constructor (like super), then it must happen on the first line of code (Note: you can only use this in this manner inside a constructor) (See: ThisConstructor.java)

Override

Not in book: You should always add @Override before every method you override (very important!) When overriding, you can change modifiers and return types under these restrictions:

  1. The modifier must be more “open” (e.g. private -> public)
  2. The return type is a descendant (child) of the original return type (e.g. Parent -> Child) (See: OverrideChild.java and OverrideParent.java)

Override vs Overload

When you override, you redefine an existing method (name) (same name, number of arguments and types) When you overload, you add a new way of using a method (name) (same name, but different arguments)