Inheritance A Review of Objects, Classes, and Subclasses.

Slides:



Advertisements
Similar presentations
AP Computer Science A – Healdsburg High School 1 Unit 3 - Classes and Objects - Example.
Advertisements

Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Inheritance Inheritance Reserved word protected Reserved word super
Inheritance Java permits you to use your user defined classes to create programs using inheritance.
Inheritance Polymorphism Briana B. Morrison CSE 1302C Spring 2010.
ITEC200 – Week03 Inheritance and Class Hierarchies.
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
1 Chapter 7 Inheritance, Polymorphism, and Scope.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Chapter 10 Classes Continued
Java Objects and Classes. 3-2 Object Oriented Programming  An OO program models the application as a world of interacting objects.  A typical Java program.
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,
CS 106 Introduction to Computer Science I 04 / 13 / 2007 Friday the 13 th Instructor: Michael Eckmann.
LESSON 2 CREATING A JAVA APPLICATION JAVA PROGRAMMING Compiled By: Edwin O. Okech [Tutor, Amoud University]
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Recap (önemli noktaları yinelemek) from last week Paradigm Kay’s Description Intro to Objects Messages / Interconnections Information Hiding Classes Inheritance.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
Objects and Classes Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary.
Inheritance Chapter 10 Programs built from objects/instances of classes An O.O. approach – build on earlier work. Use classes in library and ones you have.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Java Classes, Objects, and Events: A Preview JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria.
AP Computer Science A – Healdsburg High School 1 Unit 3 - Objects and Classes Lab: First Steps - Example.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 5 Introduction to Defining Classes
Addison Wesley is an imprint of © 2010 Pearson Addison-Wesley. All rights reserved. Chapter 12 Object-Oriented Programming Starting Out with Games & Graphics.
Object Oriented Programming
Coming up: Inheritance
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Objects and Classes Start on Slide 30 for day 2 Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Much of.
Classes, Interfaces and Packages
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
1 Class and Object Lecture 7. 2 Classes Classes are constructs that define objects of the same type. A Java class uses instance variables to define data.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
 The word static is used to declare either a ________ variable or method.  Why do we use statics?  What is Polymorphism? class In general, we use a.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
OBJECT ORIENTED PROGRAMMING II LECTURE 7 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Java Methods Objects and Classes Start on Slide 30 for day 2
Java Inheritance.
Java Methods Objects and Classes Start on Slide 30 for day 2
Presentation transcript:

Inheritance A Review of Objects, Classes, and Subclasses

Objects Can model real-world objects Can represent GUI (Graphical User Interface) components Can represent software entities (events, files, images, etc.) Can represent abstract concepts (for example, rules of a game, etc.)

Classes and Objects A class is a piece of the program’s source code that describes a particular type of object. Object-Oriented programmers write class definitions. An object is called an instance of a class. A program can create and use more than one object or instance of the same class as needed. The word instance is a good word to represent an object because it indicates an object that exists for a period of time during part or all of the time a program is running.

Difference Between a Class and an Object Characteristics fields or instance variables Behaviors (methods) Class Object A blueprint for objects of a particular type … a cookie cutter. Defines the structure (number, types) of the characteristics or attributes Defines available behaviors of its objects

Class: Car Object: a car Attributes: String model Color color int numPassengers double amountOfGas Behaviors: Add/remove a passenger Get the tank filled Report when out of gas Attributes: model = "Mustang" color = Color.YELLOW numPassengers = 0 amountOfGas = 16.5 Behaviors: car calls methods of class as needed

Class vs. Object A piece of the program’s source code Written by a programmer An entity in a running program Created when the program is running (by a constructor or another method in a driver program or other file)

Class vs. Object Specifies the structure (the number and types) of its objects’ attributes — the same for all of its objects Specifies the possible behaviors of its objects Holds specific values of attributes or characteristics; these values can change while the program is running Behaves appropriately when called upon

Classes and Source Files Each class is stored in a separate file The name of the file must be the same as the name of the class, with the extension.java public class Car {... } Car.java By convention, the name of a class (and its source file) always starts with a capital letter. (In Java, all names are case-sensitive.)

Libraries Java programs are usually not written from scratch. There are hundreds of library classes for all occasions. Library classes are organized into packages. For example: java.util — miscellaneous utility classes java.awt — windowing and graphics toolkit javax.swing — GUI development package

Import Statements You can import names for all the classes in a package by using a wildcard.*: import java.awt.*; import java.awt.event.*; import javax.swing.*; java.lang is imported automatically into all classes and programs. java.lang defines System, Math, Object, String, and other commonly used classes. Its nice to not have to take the time to import these. Imports all classes from awt, awt.event, and swing packages

public class SomeClass Fields Constructors Methods } Attributes / variables that define the object’s state; can hold numbers, characters, strings, other objects Procedures for constructing a new object of this class and initializing its fields Actions that an object of this class can take (behaviors) { Class header SomeClass.java import... import statements

Fields The word fields is used to represent not only instance variables but also class variables and class constants. Specifically: Instance variables constitute the “private memory” of an object. Class variables are usually private, but class constants are generally public. Each field has a data type (int, double, String, Image, etc.) Any field can be an object of any type. Each field has a name given by the programmer that should meaningfully describe its use.

private [static] [final] datatype name ; Types of Fields May be present: means the field is a constant int, double, etc., or an object: String, Image, SavingsAccount, etc. You name it! May be present: means the field is shared by all objects in the class Usually private

Fields Examples: private int pin; // private instance variable public static final double INTEREST_RATE = 0.025; // class constant private static int numberOfAccounts; The last example is a class variable. It is not an attribute of any object of the class, but rather it is an attribute of the class. The class (not any specific object) will maintain how many accounts have been created. Usually there is a public class method that allows a programmer to access its value.

Constructors Short procedures for creating objects of a class Always have the same name as the class Have the responsibility to initialize the object’s fields May have parameters that pass off their values to the fields A class may have several constructors that differ in the number and/or types of their parameters

Constructor Parameters public class SavingsAcount {... public SavingsAcount (int firstName, int lastName, int pin, …) {... }... } // ATM_Test.java... savings = new SavingsAcount (first, last, p, …);... The number, order, and types of parameters must match. Constructor Code Constructor Call

Constructors Documentation JButton go = new JButton("Go"); A class’s API can show you how to use constructors of the class.

Methods of a Model Class Methods of a Model class are called for a particular object. In other words, in this form: savings.deposit(amount); checking.withdrawl(amount); These kind of methods are sometimes called instance methods. These methods do not contain the word static in their method signatures. They may be accessor or mutator methods. Class methods contain the word static in their method signatures and are usually called to obtain the value of a class variable.

Example of a Class Method Example of a class method: public static int getNumberOfAccounts ( ) { return numberOfAccounts; } This method would return the value stored in the private class variable numberOfAccounts.

Parameters of Methods The number and types of parameters (a.k.a. arguments) passed to a method must match method’s parameters: g.drawString ("Welcome", 120, 50); public void drawString ( String msg, int x, int y ) {... }

Encapsulation and Information Hiding A class interacts with other classes only through constructors and public methods. Other classes do not need to know the mechanics of a class to use it effectively. In other words, a class doesn’t need to know the implementation details of how the code is written in another class. Encapsulation is the combining of attributes an behavior together to define an object. In other words, writing a model class to define the fields and methods needed for a particular kind of object. Encapsulation facilitates team work and program maintenance (making changes to the code).

The Scope of a Class’s Methods A class’s constructors and methods can call other public and private methods of the same class. However, a class’s constructors and methods can call only public methods of another class. Class X private field private method Class Y public method A method of one class can’t access any private items of another class.

Inheritance In Object Oriented Programming, a programmer can create a new class by extending an existing class. Superclass (Base class) Subclass (Derived class) subclass extends superclass

Subclasses A subclass … inherits fields and methods of its superclass can add new fields and methods can redefine (override) a method of the superclass must provide its own constructors, but calls superclass’s constructors does not have direct access to its superclass’s private fields, but has access to protected fields

Sample Structure of Inheritance Many times programmers will organize hierarchies of classes using an interface, a superclass and subclasses. Interface Super Class Subclass Class 1Subclass Class 2 You can think of the red arrow as meaning “inherits from”

Objects in a Bank Account Program In a Bank Account program we might have a SavingsAccount and a CheckingAccount, but to keep from duplicating code we might have an AbstractAccount class to accumulate the code that would be the same in those classes. An interface could also serve to further organize objects of these types to standardize the type of accounts used for our purpose. BankAccount Interface AbstractAccount Class SavingsAccount Class CheckingAccount Class You can think of the red arrow as meaning “inherits from”

Structure of an Interface public interface BankAccount { public String getFirstName(); public String getLastName(); public int getAccountNumber(); public double getBalance(); public double deposit (double d); public double withdrawl (double d); } An interface is a listing of methods that must be implemented by a class or another interface. (Yes it is possible to have a subinterface.) In the list, only the method signature of the method to be implemented followed by a semicolon is included for each method. Also, the interface definition line uses public interface instead of public class.

Declaring an Abstract Class Here is the class definition line of an abstract class that implements an interface. abstract public class AbstractShape implements Shape Notice it looks the same as a typical class definition line, except that the Java keyword abstract is added to the first of it. One thing you can’t do is instantiate an object of an abstract class. Think about that. An object of an abstract class would really be an incomplete object. It would be a partial object that would contain only some parts of an object that might be constructed of a subclass. So it would be meaningless. So to prevent an object of an abstract class from being constructed, we add the keyword abstract to the class definition line.

Final Methods of an Abstract Class As mentioned previously, an abstract class is a super class that contains the code that would be duplicated in any subclasses. An abstract class will contain fields and methods that would be the same for all subclasses that would extend it. For the methods that would be the same in any subclass, we just need to code them once in the abstract class and not in the subclasses. To do this, we place the Java keyword final at the first of the method signature to indicate that the method can’t be overridden in a subclass. If for some reason, you might want the method to be overridden in one class but not other subclasses, then you would leave off the word final.

Final Methods of AbstractShape These final methods were used in the AbstractShape class, because the code would have been exactly the same in the Circle, Rectangle, or Triangle classes. So we place it in the AbstractShape class and make the methods final. public final int getXPos() { return xPos; } public final int getYPos() { return yPos; } public final Color getColor() { return color; }

Abstract Methods of an Abstract Class For methods that will be provided by subclasses, we just provide the method signature along with the word abstract and a semicolon to end the method signature. No code or curly braces are included. If the abstract class implements an interface, it is necessary to include the word abstract with methods like this so Java knows that the subclass will be providing the method. By implementing the interface, Java is forcing the abstract class to implement the method. So if is not going to provide the method, then it must have the method signature with abstract so Java knows how it will be handled.

Abstract Methods of the AbstractShape Class These abstract methods were used in the AbstractShape class, because the code for each one in the Circle, Rectangle, and Triangle classes was different. Therefore the AbstractShape class couldn’t provide each method’s code. abstract public double area(); abstract public void draw (Graphics g); abstract public void paint (Graphics g); abstract public void move (int xLoc, int yLoc); abstract public void stretchBy (int factor);

Using the Super Keyword in Java When super is used inside a constructor, it must be the first line of code. If it is in the default constructor of a subclass and you write: super( ); then you are calling the default constructor of the superclass. If it is in an initializing constructor, and you need to pass parameters up to the superclass, then you will be calling the initializing constructor of the superclass. The code might look like this, but it still needs to be the first line of code: super(xLoc, yLoc, r, c);

Using the Super Keyword in Java When super is used inside any other method, it doesn’t have to be the first line of code. If it is in the draw method of a subclass and you write: super.draw(g); when you are calling the draw method of the super class, then it can be any place in the method.