CIT 590 Intro to Programming Lecture 13. Agenda A few topics that you have seen but might not have fully grasped Static Public, private, protected etc.

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

Object Oriented Programming with Java
24-Aug-14 Abstract Classes and Interfaces. Java is “safer” than Python Python is very dynamic—classes and methods can be added, modified, and deleted.
SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
INHERITANCE BASICS Reusability is achieved by INHERITANCE
Static Methods Static methods are those methods that are not called on objects. In other words, they don’t have an implicit parameter. Random number generation.
ABSTRACT CLASSES AND INTERFACES. Abstract methods You can declare an object without defining it: Person p; Similarly, you can declare a method without.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
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.
Road Map Introduction to object oriented programming. Classes
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,
Access to Names Namespaces, Scopes, Access privileges.
15-Jun-15 Abstract Classes and Interfaces. 2 Abstract methods You can declare an object without defining it: Person p; Similarly, you can declare a method.
1 Lecture 06(Abstract Classes)Lecture 9 Abstract Classes Overview  Abstract Classes: A Definition.  Declaring Abstract Classes.  Abstract Methods: A.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
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.
28-Jun-15 Everything You Ever Wanted To Know About Java O-O.
28-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
Abstract Classes and Interfaces. Abstract methods You can declare an object without defining it: Person p; Similarly, you can declare a method without.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
Abstract Classes and Interfaces
Object oriented design in Java (useful revision for final exam)
Abstract classes and Interfaces. Abstract classes.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
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,
Dec Abstract Classes and Interfaces. Eclipse trick CTRL + D will remove lines Organization Bookmarks TODOs – marking something as //TODO allows.
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.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Chapter 2 Introducing Interfaces Summary prepared by Kirk Scott.
Programming With Java ICS201 University Of Hail1 Chapter 13 Interfaces.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
1 final (the keyword, not the exam). 2 Motivation Suppose we’ve defined an Employee class, and we don’t want someone to come along and muck it up  E.g.,
MCS 270 Spring 2014 Object-Oriented Software Development.
Programming in Java CSCI-2220 Object Oriented Programming.
Abstract Classes and Interfaces 5-Dec-15. Abstract methods You can declare an object without defining it: Person p; Similarly, you can declare a method.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
1 Abstract Classes and Interfaces. 2 The abstract Modifier  The abstract class –Cannot be instantiated –Should be extended and implemented in subclasses.
MIT AITI 2004 – Lecture 13 Abstract Classes and Interfaces.
Lecture 21 - Abstract Classes and Interface. Example Figure –Rectangle –Triangle Figure –Dimensions –Area.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
When is a class not a class? When it is either abstract or an Interface.
Access Specifier. Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. When a member.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
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)
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
BY:- TOPS Technologies
Java Interfaces Warm-up: What is an abstract class? What is type casting?
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Modern Programming Tools And Techniques-I
Chapter 15 Abstract Classes and Interfaces
Abstract Classes and Interfaces
Abstract Classes and Interfaces
Abstract Classes and Interfaces
Some Eclipse shortcuts
University of Central Florida COP 3330 Object Oriented Programming
Android Programming Lecture 2
Advanced Java Programming
Inheritance Inheritance is a fundamental Object Oriented concept
Final and Abstract Classes
Abstract Classes and Interfaces
Abstract Classes and Interfaces
Presentation transcript:

CIT 590 Intro to Programming Lecture 13

Agenda A few topics that you have seen but might not have fully grasped Static Public, private, protected etc Exceptions Main topic = abstract classes

Inheritance questions Every class has a constructor! 0 for false 1 for true 2 for do not understand the question 1 is the answer here. A class either gets a default constructor from Java or will have one that is explicitly defined. If a class has an explicit constructor then Java stops providing it with a default no argument constructor.

What does static mean??? Simplest way of understanding static = I do not need to create an object to call this method Remember Math.sqrt? Did you create an instance of Math? A lot of times general helper functions will be found as static functions

Why static in your assignment? Constructors should never have crazy error checking But error checking is important With a static method we can do the error checking upfront before trying to do any construction. How to call a static method Squarelotron.makeSquarelotron(new int[]{1,2,3,5,6})

Public static void main? A program has to run something How does it run any method in a class without creating an instance? Answer = static! You already know what void means We will talk about public, private and protected today

When should you use a static method? When there is no need for the method to belong to an instance of the object Example? In an class like Rational you might want a method called gcd. Remember gcd(a, b) – greatest common divisor? Do you need an instance of a Rational number in order to compute the gcd of 2 numbers? No! So make it static.

More examples of static Class Car A method like convertMpgToKpl – changing the american miles per gallon to kilometres per litre. Should this method be static? Do you need a actual instance of a car in order for you to convert mpg to kpl? No Hence static

More examples of static Static is used for constant instance variables static final double PI = ; Same argument as before – we do not need to create an instance of some mathematical object to tell us the value of Pi. The extra final word is to say the value cannot be changed One final common usage is to use static variables to keep track of the number of objects created

public class Parent { static int instances = 0; public Parent() { instances += 1; } public class Child extends Parent{ public Child() { instances += 1; } public static void main(String[] args) { Parent p = new Parent(); Child c = new Child(); System.out.println(p.instances); } What gets printed?

Access modifiers Public Private Protected Nothing being written aka default = package

Style rules for access modifiers Most methods are public – that is how the objects communicate with each other Most fields/instance variables are either private or protected. If a field is private you probably do provide getters or setters Sometimes you want to make a method private No one needs to know the internal workings Any helper function you write to modularize a big main function should probably be private

Exceptions They are objects as well You can create one in the following manner IllegalArgumentException e = new IllegalArgumentException(“kaboom"); You throw one of these exceptions by saying throw e; More on exceptions in terms of try/catch in next time’s class where we talk about file processing

Declaring versus defining Person p; - declaration p = new Person(“jfk”); - defining Person p = new Person(“jfk”) – declaring and defining

3 Abstract methods You can declare an object without defining it: Person p; Similarly, you can declare a method without defining it: public abstract void draw(int size); Notice that the body of the method is missing A method that has been declared but not defined is an abstract method

4 Abstract classes I Any class containing an abstract method is an abstract class You must declare the class with the keyword abstract : abstract class MyClass {...} An abstract class is incomplete It has “missing” method bodies You cannot instantiate (create a new instance of) an abstract class

5 Abstract classes II You can extend (subclass) an abstract class If the subclass defines all the inherited abstract methods, it is “complete” and can be instantiated If the subclass does not define all the inherited abstract methods, it too must be abstract You can declare a class to be abstract even if it does not contain any abstract methods This prevents the class from being instantiated

6 Why have abstract classes? Suppose you wanted to create a class Shape, with subclasses Oval, Rectangle, Triangle, Hexagon, etc. You don’t want to allow creation of a “Shape” Only particular shapes make sense, not generic ones If Shape is abstract, you can’t create a new Shape You can create a new Oval, a new Rectangle, etc. Abstract classes are good for defining a general category containing specific, “concrete” classes

7 An example abstract class public abstract class Animal { abstract int eat(); abstract void breathe(); } This class cannot be instantiated Any non-abstract subclass of Animal must provide the eat() and breathe() methods

9 A problem class Shape {... } class Star extends Shape { void draw() {... }... } class Crescent extends Shape { void draw() {... }... } Shape someShape = new Star(); This is legal, because a Star is a Shape someShape.draw(); This is a syntax error, because some Shape might not have a draw() method Remember: A class knows its superclass, but not its subclasses

8 Why have abstract methods? Suppose you are making a GUI, and you want to draw a number of different “shapes” (marbles, pegs, frogs, stars, etc.) Each class ( Marble, Peg, etc.) has a draw method You make these subclasses of a class Shape, so that you can create an ArrayList shapes to hold the various things to be drawn You would like to do for (Shape s : shapes) s.draw(); This isn’t legal! Every class “knows” its superclass, but a class doesn’t “know” its subclasses You may know that every subclass of Shape has a draw method, but Java doesn’t Solution 1: Put a draw method in the Shape class This method will be inherited by all subclasses, and will make Java happy But what will it draw? Solution 2: Put an abstract draw method in the Shape class This will also be inherited (and make Java happy), but you don’t have to define it You do, however, have to make the Shape class abstract This way, Java knows that only “concrete” objects have a draw method

10 A solution abstract class Shape { abstract void draw(); } class Star extends Shape { void draw() {... }... } class Crescent extends Shape { void draw() {... }... } Shape someShape = new Star(); This is legal, because a Star is a Shape However, Shape someShape = new Shape(); is no longer legal someShape.draw(); This is legal, because every actual instance must have a draw() method

11 Interfaces An interface declares (describes) methods but does not supply bodies for them  interface KeyListener { public void keyPressed(KeyEvent e); public void keyReleased(KeyEvent e); public void keyTyped(KeyEvent e); } All the methods are implicitly public and abstract You can add these qualifiers if you like, but why bother? You cannot instantiate an interface An interface is like a very abstract class— none of its methods are defined An interface may also contain constants ( final variables)

12 Designing interfaces You will frequently use the supplied Java interfaces Sometimes you will want to design your own You would write an interface if you want classes of various types to all have a certain set of capabilities For example, if you want to be able to create animated displays of objects in a class, you might define an interface as: public interface Animatable { install(Panel p); display(); } Now you can write code that will display any Animatable class in a Panel of your choice, simply by calling these methods

13 Implementing an interface I You extend a class, but you implement an interface A class can only extend (subclass) one other class, but it can implement as many interfaces as you like Example: class MyListener implements KeyListener, ActionListener { … }

14 Implementing an interface II When you say a class implements an interface, you are promising to define all the methods that were declared in the interface Example: class MyKeyListener implements KeyListener { public void keyPressed(KeyEvent e) {...}; public void keyReleased(KeyEvent e) {...}; public void keyTyped(KeyEvent e) {...}; } The “... ” indicates actual code that you must supply Now you can create a new MyKeyListener

15 Partially implementing an Interface It is possible for a class to define some but not all of the methods defined in an interface: abstract class MyKeyListener implements KeyListener { public void keyTyped(KeyEvent e) {...}; } Since this class does not supply all the methods it has promised, it must be an abstract class You must label it as such with the keyword abstract You can even extend an interface (to add methods): interface FunkyKeyListener extends KeyListener {... }

16 What are interfaces for? Reason 1: A class can only extend one other class, but it can implement multiple interfaces This lets the class fill multiple “roles” In writing Applets, it is common to have one class implement several different listeners Example: class MyApplet extends Applet implements ActionListener, KeyListener {... } Reason 2: You can write methods that work for more than one kind of class

16 What are interfaces for? We used them in this Squarelotron assignment in order to give you something to begin with Also less likely to change method signatures

17 How to use interfaces You can write methods that work with more than one class interface RuleSet { boolean isLegal(Move m, Board b); void makeMove(Move m); } Every class that implements RuleSet must have these methods class CheckersRules implements RuleSet { // one implementation public boolean isLegal(Move m, Board b) {... } public void makeMove(Move m) {... } } class ChessRules implements RuleSet {... } // another implementation class LinesOfActionRules implements RuleSet {... } // and another RuleSet rulesOfThisGame = new ChessRules(); This assignment is legal because a rulesOfThisGame object is a RuleSet object if (rulesOfThisGame.isLegal(m, b)) { makeMove(m); } This statement is legal because, whatever kind of RuleSet object rulesOfThisGame is, it must have isLegal and makeMove methods

18 instanceof instanceof is a keyword that tells you whether a variable “is a” member of a class or interface For example, if class Dog extends Animal implements Pet {...} Animal fido = new Dog(); then the following are all true: fido instanceof Dog fido instanceof Animal fido instanceof Pet instanceof is seldom used When you find yourself wanting to use instanceof, think about whether the method you are writing should be moved to the individual subclasses

19 Interfaces, again When you implement an interface, you promise to define all the functions it declares There can be a lot of methods interface KeyListener { public void keyPressed(KeyEvent e); public void keyReleased(KeyEvent e); public void keyTyped(KeyEvent e); } What if you only care about a couple of these methods?