Week 11: Class Design 1.  Most classes are meant to be used more than once  This means that you have to think about what will be helpful for future.

Slides:



Advertisements
Similar presentations
Classes and Objects in Java
Advertisements

Basic Object-Oriented concepts. Concept: An object has behaviors In old style programming, you had: –data, which was completely passive –functions, which.
A subclass can add new private instance variables A subclass can add new public, private or static methods A subclass can override inherited methods A.
Inheritance Writing and using Classes effectively.
1 Chapter 6: Extending classes and Inheritance. 2 Basics of Inheritance One of the basic objectives of Inheritance is code reuse If you want to extend.
Week 11 - Friday.  What did we talk about last time?  Object methods  Accessors  Mutators  Constructors  Defining classes.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Inheritance Inheritance Reserved word protected Reserved word super
Java Inheritance. What is inherited A subclass inherits variables and methods from its superclass and all of its ancestors. The subclass can use these.
OBJECT-ORIENTED PROGRAMMING. What is an “object”? Abstract entity that contains data and actions Attributes (characteristics) and methods (functions)
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
Week 10: Objects and Classes 1.  There are two classifications of types in Java  Primitive types:  int  double  boolean  char  Object types: 
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,
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
CPSC150 Abstract Classes and Interfaces Chapter 10.
Classes with multiple methods Part 1. Review of classes & objects Early on, we learned that objects are the basic working units in object-oriented programs.
Unit 011 Inheritance Recall What Inheritance is About The extends Keyword The Object Class Overriding versus Overloading What is Actually Inherited? Single.
Abstract Classes and Interfaces
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Week 13 - Wednesday.  What did we talk about last time?  Color representation  Color class  Picture class.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
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,
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
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.
1 CSC 221: Computer Programming I Spring 2010 interaction & design  modular design: roulette game  constants, static fields  % operator, string equals.
CS125 Exam Review Winter Some Exam Info Tuesday (22nd) at 4:00-6:30pm in the PAC CHECK YOUR SEAT!!! Read Final Exam Information on website –Practice.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
CSC 142 Computer Science II Zhen Jiang West Chester University
Inheritance (Part 4) Abstract Classes 1.  sometimes you will find that you want the API for a base class to have a method that the base class cannot.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors, Encapsulation, this reading:
10-Nov-15 Java Object Oriented Programming What is it?
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.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Newport Robotics Group 1 Tuesdays, 6:30 – 8:30 PM Newport High School Week 4 10/23/2014.
1 CS 177 Week 11 Recitation Slides Class Design/Custom Classes.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Week 13 - Wednesday.  What did we talk about last time?  Color representation  Color class  Picture class.
11. Reference Organization Packages. What is reference organization? It is a process that enables us to group classes and interfaces into isolated namespaces.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
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.
Week 12 - Wednesday.  What did we talk about last time?  Hunters and prey.
CS1101 Group1 Discussion 6 Lek Hsiang Hui comp.nus.edu.sg
Week 12 - Monday.  What did we talk about last time?  Defining classes  Class practice  Lab 11.
Session 7 Introduction to Inheritance. Accumulator Example a simple calculator app classes needed: –AdderApp - contains main –AddingFrame - GUI –CloseableFrame.
A Java program consists of a set of class definitions, optionally grouped into packages. Each class encapsulates state and behavior appropriate to whatever.
Basic Object-Oriented concepts. Concept: Classes describe objects Every object belongs to (is an instance of) a class An object may have fields –The class.
Inheritance and Polymorphism
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
CS 115 Lecture 5 Math library; building a project Taken from notes by Dr. Neil Moore.
BY:- TOPS Technologies
Today Encapsulation. Build a fully encapsulated Halloween class, going from Halloween1 to Halloween6 (eventually!): –The final version will have overloaded.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors, Encapsulation, this reading:
Week 14 - Monday CS 121.
Phil Tayco Slide version 1.0 Created Oct 2, 2017
CS1316: Representing Structure and Behavior
Java Inheritance.
Final Jim Brucker.
Object-Oriented Programming
CMPE212 – Reminders Quiz 1 marking done. Assignment 2 due next Friday.
Chapter 11 Inheritance and Encapsulation and Polymorphism
Presentation transcript:

Week 11: Class Design 1

 Most classes are meant to be used more than once  This means that you have to think about what will be helpful for future programmers  There are a number of trade-offs to consider  More methods means more flexibility  Too many methods can be confusing 2

 Document thoroughly  Write documentation clearly in a way that describes what every method does ▪ Input ▪ Output ▪ Expectations  The user probably will not be able to see your code  String API example: /String.html /String.html 3

 Try to provide only the methods that are absolutely essential  Example: The Java Math library provides sin() and cos() methods but no sec() or cosec() methods  String has lots of methods, and they are great  Usually, less is more 4

 How do you make sure that your class does everything it will need to?  If you design a class to keep records about human beings, should you check to make sure that the age is in a certain range?  What range?  Make sure it’s less than 130 years?  Make sure it’s not negative? 5

 Y2K Bug  2 digits for the date was not enough, now 4  It’s all just going to get messed up in Y10K  Y2038 Bug  Unix machines often use a 32-bit integer to represent seconds since January 1, 1970  Zip Codes (5+4)  Vehicle Identification Numbers  IP Addresses 6

 IPv4 uses n1:n2:n3:n4 where each n is (like )  That allows 2 32 IP addresses (8.6 billion)  There are approximately 6.8 billion people on earth  IPv6 uses n1:n2:n3:n4:n5:n6:n7:n8  8 groups of 4 hexadecimal digits each  f7c3:0db8:85a3:0000:0000:8a2e:0370:7334  How many different addresses is this?  ≈ 3.4×10 38 is enough to have 500 trillion addresses for every cell of every person’s body on Earth  Will that be enough?! 7

 Members are the data inside objects  But, sometimes, wouldn’t it be nice if some data were linked to the class as a whole, rather than just one object?  What if you wanted to keep track of the total number of a particular kind of object you create? 8

 Static members are stored with the class, not with any particular object public class Item { private static int count = 0; // only one copy (in class) private String name;// one copy per object public Item( String s ) { name = s; count++;// updates class counter } public String getName() { return name; } public static int getTotalItems() { return count; } } 9

 Static members are also called class variables  Static members can be accessed by either static methods or regular  Static members can be either public or private 10

 Sometimes a value will not change after an object has been created:  Example: A ball has a single color after it is created  You can enforce the fact that the value will not change with the final keyword  A member declared final can only be assigned a value once  Afterwards, it can never change 11

 Using final, we can fix the value of a member  It will only be set once, usually when the constructor is called  It is customary to use all caps for constant names public class Human { private String name; private final String BIRTHPLACE; // never changes private int age; public Human( String s, String whereBorn ) { name = s; BIRTHPLACE = whereBorn; age = 0; } public void birthPlaceChange(String locn) { BIRTHPLACE = locn;// compile-time error! } 12

 It is possible to set a static member to be constant using the final keyword  Usually, this is used for global constants that will never ever change  Making these values public is reasonable  Since they never change, we never have to worry about a user corrupting the data inside of the object 13

 The number of sides of a pentagon is always 5  Other code can access this information by using the value Pentagon.SIDES  Exactly like Math.PI or Math.E public class Pentagon { private double x; private double y; public static final int SIDES = 5; // never changes public Pentagon( double newX, double newY ) { x = newX; y = newY; } public double getX() { return x; } public double getY() { return y; } } 14

 Always think about future uses of your objects and classes  Hide as much data as possible (using private )  Make as much data as possible constant (using final )  Try to use the right number of methods  Short, powerful, intuitive methods  Don’t use redundant methods that do similar things  Check the input of all methods for errors 15

 The idea of inheritance is to take one class and generate a child class  This child class has everything that the parent class has (members and methods)  But, you can also add more functionality to the child  The child can be considered to be a specialized version of the parent 16

 The key idea behind inheritance is safe code reuse  You can use old code that was designed to, say, work with Vehicle s, and apply that code Car s  All that you have to do is make sure that Car is a subclass (or child class) of Vehicle 17

 All this is well and good, but how do you actually create a subclass?  Let’s start by writing the Vehicle class public class Vehicle { … public void travel(String destination) { System.out.println(“Traveling to “ + destination); } 18

 We use the extends keyword to create a subclass from a superclass  A Car can do everything that a Vehicle can, plus more public class Car extends Vehicle { private String model; public Car(String s) { model = s; } public String getModel() { return model; } public void startEngine() { System.out.println(“Vrooooom!”); } 19

 There is a part of the Car class that knows all the Vehicle members and methods Car car = new Car(“Camry”); System.out.println( car.getModel() ); //prints “Camry” car.startEngine(); //prints “Vrooooom!” car.travel( “New York City” ); //prints “Traveling to New York City” 20

 Each Car object actually has a Vehicle object buried inside of it  If code tries to call a method that isn’t found in the Car class, it will look deeper and see if it is in the Vehicle class Car model getModel() startEngine() Car model getModel() startEngine() Vehicle travel() Vehicle travel() 21

 Sometimes you want to do more than add  You want to change a method to do something different  You can write a method in a child class that has the same signature as a method in a parent class  The child version of the method will always get called  This is called overriding a method 22

 We make the Boat class override the travel() method  In use: public class Boat extends Vehicle { public void travel(String destination) { System.out.println(“Traveling across ” + “the water to “ + destination); } Boat b = new Boat(); b.travel(“Portugal”); // prints Traveling across the water to Portugal // even though v is a Vehicle reference 23

 We can define the Mammal class as follows: public class Mammal { public void makeNoise() { System.out.println(“Grunt!”); } 24

 From there, we can define the Dog, Cat, and Human subclasses, overriding the makeNoise() method appropriately public class Dog extends Mammal { public void makeNoise() { System.out.println(“Woof”); } } public class Cat extends Mammal { public void makeNoise() { System.out.println(“Meow”); } } public class Human extends Mammal { public void makeNoise() { System.out.println(“Hello”); } } 25

 We made a Student class last week  Each Student contained  First Name: String  Last Name: String  GPA: double  ID: int  We could make a GraduateStudent class adding:  Degree : String  Advisor: String 26

 No matter how complex a program is, inside this method, only x, y, and z variables exist public class Student { private String firstName; private String lastName; private double gpa; private int id; public Student() // default constructor { firstName = “”; lastName = “”; gpa = 0.0; id = 0; } 27

 No matter how complex a program is, inside this method, only x, y, and z variables exist public Student(String first, String last, double grades, int num) // constructor { firstName = first; lastName = last; gpa = grades; id = num; } public double getGPA() // accessor { return gpa; } 28

 No matter how complex a program is, inside this method, only x, y, and z variables exist public int getID() // accessor { return id; } public String getName() // accessor { return lastName + “, “ + firstName; } 29

 No matter how complex a program is, inside this method, only x, y, and z variables exist public void setGPA(double grades) // mutator { if (grades>=0.0 && grades<=4.0) gpa = grades; else System.out.println(“Incorrect GPA”); } public void setID(int num) // mutator { if (num>=0 && num<=99999) id = num; else System.out.println(“Incorrect ID”); } 30

 No matter how complex a program is, inside this method, only x, y, and z variables exist public class GraduateStudent extends Student { private String degree; private String advisor; public GraduateStudent() // default { super(); degree = “”; advisor = “”; } 31

 No matter how complex a program is, inside this method, only x, y, and z variables exist public GraduateStudent(String first, String last, double grades, int num, String deg, String adv) // constructor { super (first, last, grades, num); degree = deg; advisor = adv; } public String getDegree() // accessor { return degree; } 32

 No matter how complex a program is, inside this method, only x, y, and z variables exist public String getAdvisor() // accessor { return advisor; } public void setDegree(String deg) // mutator { if (deg==“PhD” || deg==“MS”) degree = deg; else System.out.println(“Incorrect Degree”); } 33