Lecture 7 CS 202 Fall 2013.

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Inheritance Inheritance Reserved word protected Reserved word super
Intro to OOP with Java, C. Thomas Wu Inheritance and Polymorphism
23-May-15 Polymorphism. 2 Signatures In any programming language, a signature is what distinguishes one function or method from another In C, every function.
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
CS 2511 Fall  Abstraction Abstract class Interfaces  Encapsulation Access Specifiers Data Hiding  Inheritance  Polymorphism.
Chapter 10 Classes Continued
Unit 5 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
Inheritance using Java
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
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.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Chapter 2 Introducing Interfaces Summary prepared by Kirk Scott.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Programming in Java CSCI-2220 Object Oriented Programming.
Inheritance and Access Control CS 162 (Summer 2009)
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Classes Modeling the Object. Objects model the world Classes are programmer defined types that model the parts of a system Class serve as blueprints for.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Interfaces and Inner Classes
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
28-Dec-04polymorhism.ppt1 Polymorphism. 28-Dec-04polymorhism.ppt2 signatures in any programming language, a signature is what distinguishes one function.
Lecture 7 CS Cloneable is an interface that marks implementing classes as ones that can be "cloned", ie copied. The method that does this is normally.
9.1 CLASS (STATIC) VARIABLES AND METHODS Defining classes is only one aspect of object-oriented programming. The real power of object-oriented programming.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Comp1004: Object Oriented Design I Abstract Classes and Interfaces.
Lecture 6: Composition and Inheritance CS202 Fall 2013.
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
Lecture 5:Interfaces and Abstract Classes
Web Design & Development Lecture 9
Inheritance ITI1121 Nour El Kadri.
Lecture 12 Inheritance.
Lecture 6: Composition and Inheritance
Inheritance and Polymorphism
Data Structures and Algorithms
Lecture 6: Composition and Inheritance
Section 11.1 Class Variables and Methods
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Polymorphism 11-Nov-18.
Chapter 9 Inheritance and Polymorphism
Polymorphism 15-Nov-18.
More inheritance, Abstract Classes and Interfaces
Polymorphism 28-Nov-18.
Week 6 Object-Oriented Programming (2): Polymorphism
Advanced Java Programming
Java Inheritance.
Fundaments of Game Design
Chapter 14 Abstract Classes and Interfaces
Polymorphism 15-Apr-19.
Polymorphism 21-Apr-19.
Review of Previous Lesson
Review of Previous Lesson
CS 112 Programming 2 Lecture 02 Abstract Classes & Interfaces (2)
Chapter 11 Inheritance and Encapsulation and Polymorphism
CS2013 Lecture 2 Review of OOP.
Presentation transcript:

Lecture 7 CS 202 Fall 2013

Inheritance Concrete means particular or tangible, not abstract. Originally meant solidified or hardened. The building material was named because it has this quality The classes in the previous examples were concrete classes, ones that can be instantiated

Inheritance Classes may be abstract An abstract class cannot be instantiated, but it can have subclasses that are concrete. Abstract classes may contain data fields that will be common to all subclasses

Inheritance Abstract classes may define concrete methods, but they may also declare abstract methods An abstract method isn't defined (written) in the class, but must be defined in a subclass Subclasses that are also abstract can define the method or ignore it, leaving it to be defined in their own subclasses. A concrete class may inherit or override concrete method definitions from its superclass(es) A concrete class must define any methods which are abstract in its superclass hierarchy

Inheritance Syntax for abstract method: access modifier abstract return type name(); For example: protected abstract void accelerate(double speedIncrement); Syntax to implement a method that is abstract in the superclass: Just add @Override notation above the method code: @Override protected void accelerate(double speedIncrement){ speedInKmPerHr+=speedIncrement; }

Inheritance Use an abstract class when you expect to create subclasses that will implement some methods identically but other methods in different ways. If you don’t need any data fields and don’t need to define any methods, use an interface (next week!) instead. Implementation of multiple subclasses of the same class is another form of polymorphism.

Inheritance package vehicles; public abstract class Vehicle { protected double weightInKg; protected double speedInKmPerHr = 0; // a new vehicle should stop after it rolls off the assembly line protected Direction direction = new Direction(); // avoid null pointer exceptions by giving new vehicle the default direction 0, 0, 0 public Vehicle() { } public Vehicle(double weightInKgIn) { weightInKg = weightInKgIn; public abstract void steer(double bearing, double z); public abstract void accelerate(double speedIncrement); public String toString() { return "vehicle weighs " + weightInKg + " kg: is going " + speedInKmPerHr + ": " + direction.toString();

Inheritance package vehicleswithabstractclass; public abstract class MotorVehicle extends Vehicle { protected double engineDisplacementInCc; protected String fuelType; protected String manufacturer; public MotorVehicle(){} public MotorVehicle(double weightInKgIn, String manufacturerIn, double displacementIn, String fuelTypeIn) { super(weightInKgIn); manufacturer = manufacturerIn; engineDisplacementInCc = displacementIn; fuelType = fuelTypeIn; } public double getEngineDisplacementInCc() { return engineDisplacementInCc; public String getFuelType() { return fuelType; public String getManufacturer() { return manufacturer; // this method is unique to MotorVehicles, not common to all vehicles public void register() { System.out.println("Registered " + manufacturer + " vehicle with DMV"); public String toString() { return "manufacturer: " + manufacturer + "engine displacement: " + engineDisplacementInCc + ": fuelType: " + fuelType + ": " + super.toString(); @Override public void steer(double bearing, double z) { // supply code to steer like a motor vehicle // accelerate() is still abstract here

Inheritance package vehicleswithabstractclass; public class Car extends MotorVehicle { private String licensePlateNumber; public Car(double weightInKgIn, String manufacturerIn, double displacementIn, String fuelTypeIn, String licensePlateNumberIn){ super(weightInKgIn, manufacturerIn, displacementIn, fuelTypeIn); licensePlateNumber = licensePlateNumberIn; } public String getLicensePlateNumber() { return licensePlateNumber; public void setLicensePlateNumber(String licensePlateNumber) { this.licensePlateNumber = licensePlateNumber; public String toString() { return manufacturer + " car with plate " + licensePlateNumber + " and engine displacement " + engineDisplacementInCc + " cc " + fuelType + " engine weighs " + weightInKg + " kg and is going " + speedInKmPerHr +" KPH " + direction.toString(); @Override public void accelerate(double speedIncrement) { // supply code to accelerate like a car

Inheritance package vehicleswithabstractclass; public class Motorcycle extends MotorVehicle { private double volumeInDecibels; public Motorcycle(double weightInKgIn, String manufacturerIn, double displacementIn, double volumeInDecibelsIn) { super(); // note the difference between these assignments and the way the same task is done in the Car constructor. // This way is simpler, but might miss or require duplication of initialization logic in the superclass constructors. manufacturer = manufacturerIn; weightInKg = weightInKgIn; engineDisplacementInCc = displacementIn; fuelType = "gasoline"; speedInKmPerHr = 0; volumeInDecibels = volumeInDecibelsIn; } public double getVolumeInDecibels() { return volumeInDecibels; public void setVolumeInDecibels(double volumeInDecibels) { this.volumeInDecibels = volumeInDecibels; public String toString() { return manufacturer + " motorcycle with a " + engineDisplacementInCc + " cc " + fuelType + " engine weighs " + weightInKg + " kg and is going " + speedInKmPerHr + " KPH " + direction.toString() + " making noise at " + volumeInDecibels + " db"; @Override public void accelerate(double speedIncrement) { // accelerate like a motorcycle

Inheritance package vehicles; public abstract class Spacecraft extends Vehicle { // this class could have a hierarchy of abstract and concrete classes under it }

Inheritance package vehicleswithabstractclass; public class Driver { public static void main(String[] args) { Vehicle shredder = new Car(1000, "Mazda", 1900, "gasoline", "ABC-123"); System.out.println(shredder); shredder.accelerate(20); shredder.steer(100, 0); System.out.println(); Vehicle hindenburg = new Motorcycle(240, "BMW", 594, 80); hindenburg.steer(70, 0); hindenburg.accelerate(90); System.out.println(hindenburg); Vehicle porky = new Motorcycle(400, "Harley-Davidson", 1200, 150); porky.accelerate(150); porky.steer(180, 45); System.out.println(porky); }

Inheritance You can't instantiate an abstract class:

Inheritance A concrete class must have a definition for each inherited method. If the method was abstract in the last superclass, it must be defined in the new class:

More On Inheritance Usually a bad idea

Inheritance You can use a reference variable to get access to public methods of the variable's type and supertypes. Using methods of subtypes of the variable's type requires a cast and is usually a bad idea. This is true even though you instantiate an object of the subclass and make the variable reference it. public class Motorcycle extends MotorVehicle { private boolean sidecarPresent; … stuff omitted public void installSidecar(){ // this is a method of motorcycle. Its superclasses don't know about it sidecarPresent = true; } …

Inheritance These are both dicy ideas!

Inheritance Our hierarchy of abstraction is getting complicated: An object has actual data values. It is less abstract than the class of which it is an instance A concrete class doesn’t have data values (except constants), so it is more abstract than an object. However, all of its methods are defined, whether they were inherited from the superclass(es) or are written in the method itself, so it is less abstract than any superclass(es) it might have We may have concrete superclasses, which are more abstract than their subclasses Abstract classes are, as the name suggests, more abstract than concrete classes. They usually have methods that must be defined in their subclasses. Even if they don’t, they can never be instantiated; only their subclasses can. For these reasons, they are more abstract than concrete classes. We may have a hierarchy of abstract superclasses. Every class is a subclass of Object

Types and Data Structure Parameters Arrays and Lists (and also other data structures you will study in CS 203) can be parameterized by abstract classes An abstract class can not be instantiated. Therefore, an array or list whose type is a class will contain objects of concrete subclasses of the abstract class. mix different subclasses in any combination

Types and Data Structure Parameters package vehicles; public class Miata extends Car { public Miata(double weightInKgIn, double displacementIn) { super("Toyota", weightInKgIn, displacementIn, "gasoline"); } public String toString() { return "Camry with a " + engineDisplacementInCc + " cc gasoline engine weighs " + weightInKg + " kg and is going " + speedInKmPerHr +" KPH " + direction.toString();

Types and Data Structure Parameters package vehicles; public class ShrinerMobile extends Car { public ShrinerMobile(double weightInKgIn, double displacementIn, String fuelTypeIn) { super("Shriners' Lodge #1", weightInKgIn, displacementIn, "gasoline"); } public String toString() { return "ShrinerMobile with a " + engineDisplacementInCc + " cc gasoline engine weighs " + weightInKg + " kg and is going " + speedInKmPerHr +" KPH " + direction.toString();

Types and Data Structure Parameters

Simulators Imagine you need data to test software that will be used to process real-world measurements, like the ages of college students Sometimes you might want linearly-distributed data, but Gaussian (normal) distributions are often more realistic Random.nextGaussian() returns a double from a normal distribution with standard deviation = 1 and mean = 0. Multiply it by the desired STD and then add the desired mean

package simulator; import java. util package simulator; import java.util.Arrays; public class Grader { private double average; private double std; private int classSize; private double[] grades; private final double MINGRADE = 0; private final double MAXGRADE = 100; public enum GradingType { LINEAR, GAUSSIAN }; public Grader(double avgIn, double stdIn, int classSizeIn) { average = avgIn; std = stdIn; classSize = classSizeIn; } public static void main(String[] args) { Grader grd = new Grader(80d, 10d, 20); grd.grade(GradingType.LINEAR); grd.grade(GradingType.GAUSSIAN); private void grade(GradingType type) { Simulator sim = new Simulator(); if (type == GradingType.LINEAR) grades = sim.getLinearData(classSize, MINGRADE, MAXGRADE); if (type == GradingType.GAUSSIAN) grades = sim.getGaussianData(average, std, classSize, MINGRADE, MAXGRADE); System.out.println("\nData using distribution type: " + type + "\n"); for (int i = 0; i < grades.length; i++) { System.out.print("Student #" + i + " received a grade of "); System.out.printf("%3.1f\n", grades[i]); Arrays.sort(grades); System.out.println("Here are the sorted values from the simulator:"); for (double d : grades) System.out.printf("%3.1f\n",d);

package simulator; import java. util package simulator; import java.util.Random; public class Simulator { private double[] nums; public double[] getGaussianData(double mean, double std, int count, double min, double max) { Random r = new Random(); nums = new double[count]; double randDoub; for (int counter = 0; counter < nums.length; counter++){ randDoub = r.nextGaussian() * std + mean; // it's pretty hard to set limits for the values in a good way, so here is a hacky way. if(randDoub > max) randDoub = max; if(randDoub < min) randDoub = min; nums[counter] = randDoub; } return nums; public double[] getLinearData(int count, double min, double max) { // it would be better to make sure max < min first, but I am not implementing this in this example randDoub = r.nextDouble() * (max - min) + min;

Separate Things That Are Likely To Change Independently Grader is domain-specific (only useful for a narrow type of problem, in this case grading schoolwork) Simulator, on the other hand, does not contain anything that shows it is from an application that simulates grading. It could be used to generate test data for a very wide variety of problems This is an example of an important principle in software engineering. Separate the general from the specific, and separate things you can probably reuse from things you can't. If two things are likely to change independently of each other, don’t combine them. "When all you have is a hammer, everything looks like a nail" – folk proverb "If I had a hammer, I'd hammer in the morning, I'd hammer in the evening, all over this land. I'd hammer out danger; I'd hammer out a warning; I'd hammer out love between my brothers and my sisters, all over this land." –Pete Seeger