Yosemite National Park, California. CSE 114 Computer Science I Inheritance

Similar documents
AP Computer Science Java Subset

History OOP languages Year Language 1967 Simula Smalltalk

Java Programming Language

CS 111 Classes I 1. Software Organization View to this point:

JAVA - INHERITANCE. extends is the keyword used to inherit the properties of a class. Below given is the syntax of extends keyword.

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

J a v a Quiz (Unit 3, Test 0 Practice)

Chapter 13 - Inheritance

ICOM 4015: Advanced Programming

Inheritance, overloading and overriding

Chap 7 - Inheritance. An example from Zoology. An example from java.lang. Other terms from inheritance. parent. Mammal. child. Mouse. child.

CSE 1020 Introduction to Computer Science I A sample nal exam

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Description of Class Mutation Mutation Operators for Java

Advanced Data Structures

Part I. Multiple Choice Questions (2 points each):

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Assignment # 2: Design Patterns and GUIs

D06 PROGRAMMING with JAVA

Construction of classes with classes

Facebook Twitter YouTube Google Plus Website

Building Java Programs

Java CPD (I) Frans Coenen Department of Computer Science

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

Java Interview Questions and Answers

Design Patterns in Java

CS193j, Stanford Handout #10 OOP 3

Web Development and Core Java Lab Manual V th Semester

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Software Development with UML and Java 2 SDJ I2, Spring 2010

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Konzepte objektorientierter Programmierung

Install Java Development Kit (JDK) 1.8

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Collections.sort(population); // Método de ordenamiento

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

An Introduction To UML Class Diagrams Classes

Introduction to Object-Oriented Programming

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

Agenda. What is and Why Polymorphism? Examples of Polymorphism in Java programs 3 forms of Polymorphism

Ch 7-1. Object-Oriented Programming and Classes

Introduction to Java

CS506 Web Design and Development Solved Online Quiz No. 01

Introduction to Object-Oriented Programming

Java is an Object-Oriented Language. As a language that has the Object Oriented feature, Java supports the following fundamental concepts:

CS 106 Introduction to Computer Science I

3 Pillars of Object-oriented Programming. Industrial Programming Systems Programming & Scripting. Extending the Example.

Glossary of Object Oriented Terms

16 Collection Classes

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Java (12 Weeks) Introduction to Java Programming Language

Object Oriented Software Design

C++FA 5.1 PRACTICE MID-TERM EXAM

Introduction to Java. CS 3: Computer Programming in Java

JAVA - OBJECT & CLASSES

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

Stack Allocation. Run-Time Data Structures. Static Structures

CSE 8B Midterm Fall 2015

Sample CSE8A midterm Multiple Choice (circle one)

Note: Syntactically, a ; is needed at the end of a struct definition.

Programming Language Concepts: Lecture Notes

Object-Oriented Programming: Polymorphism

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Chapter 2 Introduction to Java programming

Programmation 2. Introduction à la programmation Java

LAB 1. Familiarization of Rational Rose Environment And UML for small Java Application Development

2009 Tutorial (DB4O and Visual Studio 2008 Express)

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A

RMI Client Application Programming Interface

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

If too much money is inserted the machine takes it all - no refund. If there isn't enough money inserted, it still prints out the ticket.

How Scala Improved Our Java

Contents. 9-1 Copyright (c) N. Afshartous

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Crash Course in Java

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Object-Oriented Programming in Java: More Capabilities

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Section 6 Spring 2013

Object-Oriented Programming in Java

CS170 Lab 11 Abstract Data Types & Objects

Smallest Java Package? Java.applet.* having 1 class and 3 interfaces. Applet Class and AppletContext, AppletStub, Audioclip interfaces.

Automatic generation of fully-executable code from the Domain tier of UML diagrams

The Interface Concept

Topic 11 Scanner object, conditional execution

Introduction to Object-Oriented Programming

JAVA - METHODS. Method definition consists of a method header and a method body. The same is shown below:

C++ Programming Language

15-214: Principles of Software Construction 8 th March 2012

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For

Inside the Java Virtual Machine

Konzepte objektorientierter Programmierung

Learn About UML Class Schemas Object and Methods in Java

CSC 221: Computer Programming I. Fall 2006

Transcription:

Yosemite National Park, California CSE 114 Computer Science I Inheritance

Containment A class contains another class if it instantiates an object of that class HAS-A also called aggregation PairOfDice HAS-A Die

Inheritance One class can be derived from another class inherits its instance variables and methods child class -----> parent class IS-A subclass class derived class base class Any instance variable or method that is inherited by a subclass does not need to be redefined in the subclass.

Why use Inheritance? Customize classes (from the JDK or your own) Benefits: Don t have to re-write code Abstraction the JDK has many classes to customize, especially for GUIs Use methods and variables of fully tested classes Code in super classes can be used by a limitless number of subclasses Making changes to common properties is easier just change the parent class

Inheritance is powerful And the real reason? Why? Code written today can call methods written 10 years from now Huh? That s due to inheritance & polymorphism, more on this next lecture

Inheritance Syntax public class ChildClass extends ParentClass { // instance variables for Child only // methods for Child only ChildClass now contains all instance variables and methods defined above, as well as those defined inside ParentClass

How to organize classes using Inheritance Determine what data you need to store. For example, for storing student and employee data: Student data: name, age, GPA Employee data: name, age, salary Divide up your classes according to state since Students and Employees store different data, use separate classes Pool common data into a common parent class Person data: name, age Have Student and Employee classes customize Person

Example: Parent Class: Person public class Person { private String name; private int age; // constructor public Person(String initname) { age = 0; // just born name = initname; // accessor method public String getname() { return name; // accessor method public int getage() { return age; // mutator method public void setage(int newage) { if (newage < 0) age = 0; else age = newage;

Example: Child (Sub-)Class: Student public class Student extends Person { private double gpa; // constructor for a Student public Student(String initname) { super(initname); gpa = 0.0; Means Student inherits all instance variables and methods from Person Runs Person s constructor public double getgpa() { return gpa; public void setgpa(double newgpa) { if (newgpa < 0.0 newgpa > 4.0) gpa = 0.0; else gpa = newgpa;

Example: Child (Sub-)Class: Employee public class Employee extends Person { private int salary; // constructor for an Employee public Employee(String initname) { super(initname); salary = 0; public int getsalary() { return salary; public void setsalary(int newsalary) { if (newsalary < 0 newsalary > 400000) salary = 0; else salary = newsalary;

How much memory do they need? When we construct a Student? age: 4 bytes name: 4 bytes for String memory address more memory for String data itself of course gpa: 8 bytes How about an Employee? age: 4 bytes name: 4 bytes for String memory address salary: 4 bytes

Example: Using all three classes public class PeopleTester { public static void main(string[] args) { Person moe = new Person("Moe Stooge"); Student larry = new Student("Larry Stooge"); Employee curly = new Employee("Curly Stooge"); moe.setage(106); moe.setgpa(2.2); moe.setsalary(100000); // LEGAL? // LEGAL? // LEGAL? YES! NO! NO! larry.setage(101); larry.setgpa(1.2); larry.setsalary(50000); // LEGAL? // LEGAL? // LEGAL? YES! YES! NO! curly.setage(100); curly.setgpa(0.5); curly.setsalary(25000); // LEGAL? // LEGAL? // LEGAL? NO! YES! YES!

Inheritance: public vs. private Inherited methods are accessible by the derived class if they are public or protected. Inherited instance variables are not directly accessible by the derived class if they are private. Use public accessor/mutator methods of parent class instead. For example, if we added a clear method inside Student: public void clear() { age = 0; gpa = 0.0; ILLEGAL public void clear() { setage(0); gpa = 0.0; LEGAL private methods of a base class are not accessible by the derived class.

Inheritance: super() and this() super() runs base (parent) class' constructor Must be first statement in a derived class' constructor If it is left out, super() is still executed using the base class' default constructor (with no parameters) this() runs a class' own constructor Used on first line of another constructor May pass parameters to this() as long as they correspond to parameters for another constructor For example, if we added a new constructor for Student: public Student(String initname, double initgpa) { this(initname); gpa = initgpa; Runs the previously defined Student constructor

Inheritance: Overriding Methods A method is overridden if it is redefined in a derived class (child class) using the same method Signature. Person (parent class): public void reset() { age = 0; Student (child class): public void reset() { setage(0); gpa = 0.0; OR, Calling an overridden method: public void reset() { super.reset(); gpa = 0.0; What happens if you forget super?

Method Summary protected Object The Object class Every class is a subclass of the java.lang.object class, even if not specified directly. clone() Creates and returns a copy of this object. boolean equals(object obj) Indicates whether some other object is "equal to" this one. String tostring() Returns a string representation of the object. Automatically Called on an object whenever it is placed inside System.out.print( The 3 methods above are overridden nearly every time a new class is defined. The Object class also contains 8 other methods we won t use

Overriding tostring() method Example public class Person { public String tostring() { return name + ", age " + age; public class Student extends Person { public String tostring() { return super.tostring() + ", GPA: " + gpa; public class Employee extends Person { public String tostring() { return super.tostring() + ", Salary: $" + salary;

Printing using tostring() public class StoogePrinter { public static void main(string[] args) { Person moe = new Person("Moe Stooge"); Student larry = new Student("Larry Stooge"); Employee curly = new Employee("Curly Stooge"); System.out.println(moe.toString()); System.out.println(larry.toString()); System.out.println(curly); OUTPUT: Moe Stooge, age 0 Larry Stooge, age 0, GPA: 0.0 Curly Stooge, age 0, Salary: $0

public class Course { public int coursenumber = 114; public class Classroom { public String building = "Javits"; public int roomnumber = 100; public String tostring() { return building + roomnumber; Exercise to try at home public class LectureHall extends Classroom { public int capacity = 650; public class ToStringExample { public static void main(string[] args) { System.out.println(new Course()); System.out.println(new Classroom()); System.out.println(new LectureHall()); What output do you get?

Multiple Inheritance A class may extend only 1 class, however, when it does so it also inherits all methods and variables that the parent class has already inherited Example: public class Instructor extends Employee { private String dept; public Instructor(String initname) { super(initname); dept = "None Assigned"; public String getdept() { return dept; public void setdept(string newdept) { dept = newdept; public String tostring() { return super.tostring() + ", Dept: " + dept; public static void main(string[] args) { Instructor me = new Instructor("Richard McKenna"); System.out.println(me); OUTPUT: Richard McKenna, age 0, Salary: $0, Dept: None Assigned

Inheritance Diagrams Think of an inheritance diagram as a family tree for classes, except for a couple of differences: A class may only have 1 immediate parent No criss-crossing in a class tree Every class has all the properties (state and behavior) of all of it s ancestors (so much for Darwinism) Student Person Employee Instructor A class may have any number of ancestors, in this case Instructor has 2.

Inheritance Diagrams family tree? The Town Drunk Mama Uncle Ernie Mary Joe Joe Bob Farmer s daughter across state line Old Man Up the Mountain Elvira Fat Irma Little Bob Cletus Mary Joe Elvis Selma Sue Danger: The family tree is crossing!

Inheritance Diagram Example Object Component A class may only have 1 immediate parent No criss-crossing in a class tree Container JComponent Window JPanel AbstractButton Frame JButton JFrame

Interfaces An interface is a collection of abstract methods that are defined by all classes that implement it. cannot be instantiated includes headers for the methods but no implementation generally used to force a class to implement certain methods public interface Clock { public void set(int hour, int minute); public String gettime(); public class Watch implements Clock { // CLASS DEFINITION FOR Watch GOES HERE // MUST define public methods set() and gettime()