lecture10

lecture10 - PIC 20A Lecture 10 Inheritance What is...

Info iconThis preview shows pages 1–7. Sign up to view the full content.

View Full Document Right Arrow Icon
PIC 20A Lecture 10: Inheritance
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
What is inheritance? Inheritance is a mechanism for building a new class by extending an existing one. The new derived class inherits behavior and attributes of an existing base class, yet has unique characteristics of its own
Background image of page 2
Suppose we had two classes with similar fields and methods: public class Athlete { private String _name; private int _age; private String _sport; public String getName(){ return _name; } public String getSport(){ return _sport; } } public class Student{ private String _name; private int _age ; private double _gpa; public String getName(){ return _name; } public double getGPA(){ return _gpa; } }
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Define a superclass that contains those common members public class Person { protected String _name; protected int _age; public Person(String name, int age){ _name = name; _age = age; } public String getName(){ return _name; } } Make protected the private common members we want both Student and Athlete to inherit.
Background image of page 4
Now make Student and Athlete subclasses of Person public class Athlete extends Person { private String _sport; public String getSport(){ return _sport; } } public class Student extends Person { private double _gpa; public double getGPA(){ return _gpa; } } Athlete and Student objects are Person objects and thus have their own inherited _name and _age protected members . They also have an inherited public String getName() method
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
How does inheritance work? 1. A subclass inherits all the members
Background image of page 6
Image of page 7
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 04/12/2010 for the course PIC PIC 20A taught by Professor Keithouellette during the Spring '09 term at UCLA.

Page1 / 20

lecture10 - PIC 20A Lecture 10 Inheritance What is...

This preview shows document pages 1 - 7. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online