Lecture 6: Composition and Inheritance CS202 Fall 2013.

Slides:



Advertisements
Similar presentations
More on Classes Inheritance and Polymorphism
Advertisements

Object Oriented Programming with Java
Week 8 Recap CSE 115 Spring Composite Revisited Once we create a composite object, it can itself refer to composites. Once we create a composite.
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
LECTURE 7: INHERITANCE CSC 212 – Data Structures.
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
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,
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
CSE 115 Week 10 March , Announcements March 21 – Lab 7 Q & A in lecture March 21 – Lab 7 Q & A in lecture March 26 – Exam 7 March 26 – Exam.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
Chapter 10 Classes Continued
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
Inheritance One of the biggest advantages of object-oriented design is that of inheritance. A class may be derived from another class, the base class.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
1 Abstract Class There are some situations in which it is useful to define base classes that are never instantiated. Such classes are called abstract classes.
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.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
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.
Question of the Day  Thieves guild states it will sell to members: lock picking kits  $0.67 each 40’ rope  $2.12 each Wire cutters  $4.49 each How.
JAVA COURSE 1 Computer Engineering Association. Compile your first program Public class Hello{ public class Hello(){ System.out.println(“Hello”); } puclic.
Problem of the Day  What is the smallest positive integer that cannot be defined in less than twenty-five syllables?
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.
Question of the Day  Thieves guild states it will sell to members: lock picking kits  $0.67 each 40’ rope  $2.12 each Wire cutters  $4.49 each How.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
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.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
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.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
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.
Inheritance and Polymorphism. Superclass and Subclass Inheritance defines a relationship between objects that share characteristics. It is a mechanism.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Comp1004: Object Oriented Design I Abstract Classes and Interfaces.
Lecture 5:Interfaces and Abstract Classes
Lecture 7 CS 202 Fall 2013.
Inheritance ITI1121 Nour El Kadri.
Lecture 12 Inheritance.
Lecture 6: Composition and Inheritance
Inheritance and Polymorphism
Lecture 6: Composition and Inheritance
Inheritance in Java.
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Chapter 9 Inheritance and Polymorphism
Week 6 Object-Oriented Programming (2): Polymorphism
Java Inheritance.
Chapter 14 Abstract Classes and Interfaces
Presentation transcript:

Lecture 6: Composition and Inheritance CS202 Fall 2013

Composition Compose: to create something by combining other things In programming, Composition occurs when a class includes variables of other classes We have been doing this all along whenever we write classes that contain Strings or Scanners. Several of the lecture examples have contained variables that referred to objects of classes defined in the examples. – GradeBook above contains an array list of Students – CollegeDriver from lecture 5 contained an array list of departments, and each department contained an array list of Courses Hierarchies like this can be of any depth. Double contains a compareTo() method. Since Student.gpa is a Double, Student.compareTo() could have been written this way: – return this.gpa.compareTo(otherStudent.gpa);

Inheritance 3 Classes often have natural hierarchies, which can be defined in terms of data or in terms of functionality The simplest form of hierarchy is general-to- specific

Inheritance 4 All vehicles have some variables in common – weight – source of locomotion – manufacturer Motor vehicles are a subset of vehicles, and they have additional data fields – Engine displacement – Fuel type Trucks are a subset of motor vehicles, and they have yet more data fields – Hauling capacity – Etc

Inheritance We can model this kind of general-to-specific hierarchy using class inheritance “Super” means above, as in supervisor. “Sub” means under or below, as in submarine. A subclass is a class which is a more specific form of some other class, which we call its superclass Superclasses are more abstract than their subclasses The terms parent and child are sometimes used in place of superclass and subclass. To define a class as a subclass of a superclass, use the extends keyword. See the examples below

Inheritance Hierarchy A class can inherit from a hierarchy of superclasses, in the same way you have parents, grandparents, great-grandparents, etc. All Java classes are subclasses of Object. Object is, for example, where the original forms of toString() is defined. However, most other classes do not inherit directly from Object. – Here is the class hierarchy for OutOfMemoryError java.lang.Object java.lang.Throwable java.lang.Error java.lang.VirtualMachineError java.lang.OutOfMemoryError

Inheritance Subclasses inherit the methods and variables of their superclasses. Subclasses can add variables, constants, and methods which are not present in their superclasses.

Overriding Subclasses can also replace methods inherited from superclasses with their own methods. This is called overriding. – toString()! – Use annotation – Make the superclass methods public or protected; can’t override private methods Subclass constructors call superclass constructors. If superclass has a no-argument constructor, it is called by default by a no-argument subclass constructor – See example

Single Inheritance C++ allows a class to have more than one parent class. This is called “multiple inheritance”. Most programmers find this confusing. – The superclasses might have variables or methods with the same names In Java, a class is allowed to inherit from only one parent class. This is called “single inheritance”

Inheritance package vehicles; public class Vehicle { protected double weightInKg; protected double speedInKmPerHr; protected Direction direction; public Vehicle() { } public Vehicle(double weightInKgIn, double speedIn) { weightInKg = weightInKgIn; speedInKmPerHr = speedIn; direction = new Direction(0, 0); } public void steer(double bearing, double angle) { direction.setDirection(bearing, angle); } public void accelerate(double speedIncrement) { speedInKmPerHr += speedIncrement; } public String toString() { return "vehicle weighs " + weightInKg + " kg: is going " + speedInKmPerHr + ": " + direction.toString(); }

Inheritance package vehicles; public class Direction { private double bearing, angleToGround; public Direction(double bearingIn, double angleIn){ bearing = bearingIn; angleToGround = angleIn; } public void setDirection(double bearingIn, double angleIn){ bearing = bearingIn; angleToGround = angleIn; } // setters and getters omitted public String toString(){ return "Bearing: " + bearing + ": Angle: " + angleToGround; }

Inheritance package vehicles; public class MotorVehicle extends Vehicle { private double engineDisplacementInCc; private String fuelType; public MotorVehicle() { // this one implicitly calls Vehicle's constructor } public MotorVehicle(double weightInKgIn, double speedIn, double displacementIn, String fuelTypeIn) { super(weightInKgIn, speedIn); engineDisplacementInCc = displacementIn; fuelType = fuelTypeIn; } // also override steer() to change direction in a way appropriate for a car // getters and setters omitted public String toString() { return "engine displacement; " + engineDisplacementInCc + ": fuelType; " + fuelType + ": " + super.toString(); }

Inheritance package vehicles; public class Car extends MotorVehicle { private double throttleSetting; private String manufacturer; public Car(double weightInKgIn, double speedIn, double displacementIn, String fuelTypeIn, String manufacturerIn) { super(weightInKgIn, speedIn, displacementIn, fuelTypeIn); manufacturer = manufacturerIn; throttleSetting = 0; public void accelerate(double speedIncrement) { double origSpeed = speedInKmPerHr; while (speedInKmPerHr < origSpeed + speedIncrement && throttleSetting <= 10) { graduallyOpenThrottle(speedIncrement); } // then close the throttle a little, etc. } private void graduallyOpenThrottle(double speedIncrement) { // use your imagination. This is a cheap example throttleSetting = 3; speedInKmPerHr += speedIncrement; } public String toString() { return "Manufacturer; " + manufacturer + ": throttle; " + throttleSetting + ": " + super.toString(); }

Inheritance package vehicles; public class Driver { public static void main(String[] args) { Car shredder = new Car(1000, 100, 2400, "gasoline", "Mazda"); System.out.println(shredder); shredder.accelerate(20); shredder.steer(270, 15); System.out.println(shredder); }

Inheritance 15 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 16 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 17 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 18 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 notation above the method protected void accelerate(double speedIncrement){ speedInKmPerHr+=speedIncrement; }

Inheritance 19 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 20 package vehicles; public class Direction { private double bearing, angleToGround; public Direction(){} public Direction(double bearingIn, double angleIn){ bearing = bearingIn; angleToGround = angleIn; } public void setDirection(double bearingIn, double angleIn){ bearing = bearingIn; angleToGround = angleIn; } public String toString(){ return "Bearing: " + bearing + ": Angle: " + angleToGround; }

Inheritance 21 package vehicles; public abstract class Vehicle { protected double weightInKg; protected double speedInKmPerHr; protected Direction direction; protected abstract void accelerate(double speedIncrement); protected abstract void register(); protected abstract void steer(double bearing, double angle); }

Inheritance 22 package vehicles; public abstract class MotorVehicle extends Vehicle { protected double engineDisplacementInCc; protected String fuelType; protected String manufacturer; public void register() { System.out.println("Registered " + manufacturer + " vehicle with DMV"); }

Inheritance 23 package vehicles; public class Car extends MotorVehicle { public Car(String manufacturerIn, double weightInKgIn, double displacementIn, String fuelTypeIn){ manufacturer=manufacturerIn; weightInKg = weightInKgIn; engineDisplacementInCc = displacementIn; fuelType = fuelTypeIn; speedInKmPerHr = 0; direction = new Direction(); protected void steer(double bearing, double angle) { // replace the following with code to steer a car direction = new Direction(bearing, angle); protected void accelerate(double speedIncrement) { // replace the following with code to accelerate like a car speedInKmPerHr += speedIncrement; } public String toString() { return manufacturer + " car with a " + engineDisplacementInCc + " cc " + fuelType + " engine weighs " + weightInKg + " kg and is going " + speedInKmPerHr +" KPH " + direction.toString(); }

Inheritance 24 package vehicles; public class Motorcycle extends MotorVehicle { public Motorcycle(String manufacturerIn, double weightInKgIn, double displacementIn, String fuelTypeIn){ manufacturer=manufacturerIn; weightInKg = weightInKgIn; engineDisplacementInCc = displacementIn; fuelType = fuelTypeIn; speedInKmPerHr = 0; direction = new Direction(); } public Motorcycle(String manufacturerIn, double weightInKgIn, double displacementIn){ manufacturer=manufacturerIn; weightInKg = weightInKgIn; engineDisplacementInCc = displacementIn; fuelType = "gasoline"; speedInKmPerHr = 0; direction = new Direction(); protected void accelerate(double speedIncrement) { // replace the following with code to accelerate like a motorcycle speedInKmPerHr += speedIncrement; protected void steer(double bearing, double angle) { // replace the following with code to steer a motorcycle direction=new Direction(bearing, angle); } public String toString() { return manufacturer + " motorcycle with a " + engineDisplacementInCc + " cc " + fuelType + " engine weighs " + weightInKg + " kg and is going " + speedInKmPerHr +" KPH " + direction.toString(); }

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

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

Inheritance 27 You can't instantiate an abstract class:

Inheritance 28 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 29 Usually a bad idea

Inheritance 30 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 31 These are both dicy ideas!

Inheritance 32 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

.jar files.jar files are used for distributing Java applications and libraries. The file format is.zip, but the extension.jar identifies them as Java Archives They contain bytecode (.class files), any other files from the application or library (like images or audio files), and can also contain source code The JDK contains command line tools for making jar files, but this is easier to do with Eclipse Jar files may be executable, meaning that they are configured to launch the main() of some class contained in the jar

.jar files