CS 21b Intro to Computing II. Object-Oriented Programming: Classes in Java.

Slides:



Advertisements
Similar presentations
1 Classes and Objects in Java Basics of Classes in Java.
Advertisements

Final and Abstract Classes
OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
Inheritance Inheritance Reserved word protected Reserved word super
ITEC200 – Week03 Inheritance and Class Hierarchies.
Chapter 41 Defining Classes and Methods Chapter 4.
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.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Java Class and Inheritance.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Inheritance and Polymorphism Recitation – 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 9 Objects and Classes.
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.
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
Java Programming Review (Part I) Enterprise Systems Programming.
OOP Languages: Java vs C++
Abstract classes and Interfaces. Abstract classes.
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Lecture 3 Casting Abstract Classes and Methods Interfaces.
Eclipse – making OOP Easy
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.
Internet Software Development Classes and Inheritance Paul J Krause.
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.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and.
Programming Languages and Paradigms Object-Oriented Programming.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
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.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 5 Introduction to Defining Classes
Object Oriented Programming
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
1 The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference()
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
1 Functions/Methods. 2 Function / Method zDefinition Õcollection of statements that may be invoked by name (from another function or method) zFunctions/methods.
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.
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.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
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.
Modern Programming Tools And Techniques-I
Topic: Classes and Objects
Inheritance-Basics.
Inheritance and Polymorphism
OBJECT ORIENTED PROGRAMMING II LECTURE 7 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Java Programming Language
Java – Inheritance.
Presentation transcript:

CS 21b Intro to Computing II

Object-Oriented Programming: Classes in Java

Object Definition: a thing that has identity, state, and behavior identity: a distinguished instance of a class state: collection of values for its variables behavior: capability to execute methods * variables and methods are defined in a class

Class Definition: a collection of data (variables) and methods that operate on that data data/methods define the contents/capabilities of the instances (objects) of the class object creation occurs with the statement variable = new class(parameters); classes can be viewed as factories for objects

Class A class is a template for an object An object is an instance of a class

Class All data and variables defined within a class are called instance variables because each instance of that class (each object of the class) contains a copy of that variable Methods and variables defined within a class are called members of that class

Two Kinds of Variables in Java Variables of a primitive type e.g., int x; char c; Variables of a reference type (class) e.g., Button b; String s; Conventions Primitive types are reserved words in Java and are indicated in all-lower-case letters Class names: first letter usually capitalized

Variables and Values Primitive type variables int x; … x = 5; 5 X X

Variables and References Reference type variables Button x; … x = new Button(“click”); X X “click” Button Object

The new Keyword new Button(“click”) creates a Button object and returns a reference (an address) to that object that a Button variable could hold “click” Button Object 1023: 1023 is some address in memory 1023 X

The Dot (“.”) Operator Allows access to variables (primitive and reference types) and methods of reference type variables. Ex. TextField t = new TextField(10); t.setText(“hi”); *accessing a method using the dot operator

Method Invocation Syntax for method invocation object.methodName(arguments) Method may return a value or simply produce an effect on the object To find out what methods are available for a given class javap package.name.NameOfClass ex. Javap java.awt.Button

Strings Revisited Strings are objects as well String is an existing Java class s = “Hello” is just a shorthand for s= new String(“Hello”); String methods int length() String substring(int x,int y); no “manipulating” methods

Variables and Objects Let Circle be a class with: variable r that indicates its radius method area() that computes its area Declaration:Circle c; Instantiation:c = new Circle(); Usage: c.r = 5.5; System.out.println(c.area());

The complete Circle class public class Circle { public double x,y; // center coordinates public double r; // radius // the methods public double circumference() { return 2*3.14*r; } public double area() { return 3.14*r*r; } }

Using the Circle class public class TestCircle { public static void main(String args[]) { Circle c; c = new Circle(); c.x = 2.0; c.y = 2.0; c.r = 5.5; System.out.println(c.area()); }

The this keyword this refers to the current object In the Circle class, the following definitions for area() are equivalent: public double area() { return 3.14 * r * r; } public double area() { return 3.14 * this.r * this.r; } Using the keyword clarifies that you are referring to a variable inside an object

Constructors A constructor is a special type of method has the same name as the class It is called when an object is created new Circle(); // “calls” the Circle() method If no constructor is defined, a default constructor that does nothing is implemented

A constructor for the Circle class public class Circle { public double x,y; // center coordinates public double r; // radius public Circle() { // sets default values for x, y, and r this.x = 0.0; this.y = 0.0; this.r = 1.0; }... }

A constructor with parameters public class Circle { … public Circle(double x, double y, double z) { this.x = x; this.y = y; this.r = z; // using this is now a necessity }... }

Using the different constructors Circle c, d; c = new Circle(); // radius of circle has been set to 1.0 System.out.println(c.area()); d = new Circle(1.0,1.0,5.0); // radius of circle has been set to 5.0 System.out.println(d.area());

Method Overloading In Java, it is possible to have several method definitions under the same name but the signatures should be different Signature: the name of the method the number of parameters the types of the parameters

Fill in the blanks... Constructor without a parameter public classname() { *body of the constructor }

Fill in the blanks... Overloading constructors public classname(type variable- name) { *body of constructor } public classname( type variable-name, type variable-name) { *body of constructor }

Encapsulation A key OO concept: “Information Hiding” Key points The user of an object should have access only to those methods (or data) that are essential Unnecessary implementation details should be hidden from the user In Java, use public and private

Access Modifiers public a public variable/method is available for use outside the class it is defined in private a private variable/method may be used only within the class it is defined in

The Circle class Revisited public class Circle { private double x,y; // center coordinates private double r; // radius //... } // when using the Circle class... Circle c; c.r = 1.0; // this statement is not allowed

Outside access to private data No direct access Define (public) set and get methods instead or initialize the data through constructors Why? If you change your mind about the names and even the types of these private data, the code using the class need not be changed

Set and Get Methods Variables/attributes in a class are often not declared public Instead: define use a (public) set method to assign a value to a variable define a get method to retrieve that value Consistent with encapsulation

Set and Get Methods for Radius public class Circle { //... private double r; // radius // … public void setRadius(double r) { this.r = r; } public double getRadius() { return this.r; } //... }

Inheritance

Subclasses and Inheritance Inheritance: programming language feature that allows for the implicit definition of variables/methods for a class through an existing class In Java, use the extends keyword public class B extends A { … } objects of subclass B now have access* to variables and methods defined in A

The EnhancedCircle class public class EnhancedCircle extends Circle { // as if area(), circumference(), setRadius() and getRadius() // automatically defined; x,y,r are also present (but are private // to the the Circle class) private int color; public void setColor(int c) { color = c; } public void draw() { … } public int diameter() { return getRadius()*2;} }

Using a Subclass EnhancedCircle c; c = new EnhancedCircle(); // Circle() constructor // implicitly invoked c.setColor(5); c.setRadius(6.6); System.out.println(c.area()); System.out.println(c.diameter()); c.draw();

Applets and Inheritance Java Applets that we write extend the Applet class (defined in package java.applet) Methods such as add() (for adding visual components) are actually methods available in the Applet class init(), action(), and paint() are also available but can be overridden

Class Hierarchy Subclass relationship forms a hierarchy Example: TextField class TextField extends TextComponent which extends Component which extends Object Object is the topmost class in Java Exercise (use javap): determine where the methods setText(), getText(), hide(), and show() are defined

Method Overriding A method (with a given signature) may be overridden in a subclass Suppose class B extends A let void operate() be a method defined in A void operate() may be defined in B objects of class A use A’s operate() objects of class B use B’s operate()

Dynamic Binding Let A be a superclass of subclasses B and C A variable of class A may refer to instances of A, B, and C Java facilitates the calling of the appropriate method at run time Example A v; … v.operate();

Constructors and Superclasses Suppose B extends A new B() calls B’s constructor how about A’s constructor ? Rule the constructor of a superclass is always invoked before the statements in the subclass’ constructor are executed

super() Used to call a superclass’ constructor Implicitly included when not indicated If B extends A, the following are equivalent:public B() { // body of constructor super(); } // body of constructor }

Calling a particular Constructor Use super with parameters if a particular constructor should be called Example: public class BlueButton extends Button { public BlueButton(String s) { super(s); // without this, super() is called (label-less) setBackground(Color.blue); } … }

Default Constructors When no constructors are defined a default constructor with no parameters is implicitly included If at least one constructor is defined, with or without parameters a default constructor will not apply

Fill in the blanks... Extends and Super public class subclass extends superclass { public subclassconstructor(...) { super(...); *body of constructor }... }

Abstract Classes and Interfaces

“Incomplete” Classes Objects vs “concepts” Example: Circle and Shape circles are shapes (Circle extends Shape) shapes (such as circle) have area and circumference how are area() and circumference() defined at the level of Shape? Shape has incomplete definitions

The Shape class One option make area() and circumference() methods that do nothing (perhaps return 0.0) Circle could extend shape and then override these methods problems ? Another option available in Java abstract class

Abstract Class Same as class but it is possible to omit method bodies syntax: abstract before class (and method headers) semicolon at the end of the method headers Rules may declare variables of abstract classes instantiation not possible (new will not work) subclasses must override incomplete methods

The Shape class public abstract class Shape { private int color; public void setColor(int c) { color = c; } public abstract double circumference(); public abstract double area(); }

The Circle class public class Circle extends Shape { private double r; … // the compiler will complain if the ff methods are not defined public double circumference() { return 2*3.14*r; } public double area() { return 3.14*r*r; } }

Using Shape and Circle Circle c; Shape s; c = new Circle(); // ok s = new Shape(); // not allowed -- Shape is abstract s = new Circle(); // ok because Circle is a // subclass of Shape

Another Example: Function Plotter Define an abstract class FunctionPlotter that plots a mathematical function f() a method plot() plots a function f() by evaluating f() on some x values make f() an abstract method, i.e., public abstract double f(double x); Next, define classes that extend FunctionPlotter and complete the definition of f()

Function Plotter, continued LinePlotter defines f() as follows: public double f(double x) { return x; } SquarePlotter defines f() as follows: public double f(double x) { return x*x; } Note: LinePlotter, SquarePlotter (and Circle, in the previous example) are called concrete classes

Why Use Abstract Classes? More robust code no need to use “new” on anything it shouldn’t be used on Enforces discipline Abstract classes cannot be instantiated; they are meant to be extended Anyone who extends an abstract class is now forced to define the incomplete parts

Interface None of the methods have bodies Instance variables not allowed Syntax interface not class no need to put abstract before method headers implements not extends on the complete (concrete) class

Rules on Interfaces May declare variables whose type is an interface objects that are instances of classes that implement the interface may be referred to by such variables Instantiation not possible Implementing class must define all methods

Example public interface Switch { public void turnOn(); public void turnOff(); public boolean isOn(); } public class Computer implements Switch { // must define turnOn(), turnOff(), and isOn() in this class... }

Notes on Interfaces Interface variables can be declared e.g., Switch s; Interfaces cannot be instantiated Interface variables may refer to objects of classes that implement the interface e.g., s = new Computer(); A class may implement several interfaces

Multiple Inheritance Other OO languages such as C++ allow several superclasses for a given class not possible in Java Implementation problems common members in superclasses In Java use interfaces it is possible to implement several interfaces with no “conflicts”

Anonymous Classes Feature available in JDK 1.1 or higher versions of Java Useful when Only one object of the concrete class needs to be created It is not too important to have a name for the concrete class

Back to FunctionPlotter Example Without anonymous classes, the LinePlotter class would look like this public class LinePlotter extends FunctionPlotter { public double f(double x) { return x; } } And then, in some main program … LinePlotter lp = new LinePlotter(); lp.plot();

Using Anonymous Classes FunctionPlotter lp = new FunctionPlotter() { public double f(double x) { return x; } } lp.plot(); // no need to explicitly define a LinePlotter class

Fill in the blanks... Anonymous classes abstractclassorinterface var = new abstractclassorinterface() { // complete the definitions of abstract // methods here }

The Java Event Models

Event-Driven Programming in Java Specifying actions for events performed on the GUI most common example: clicking on a button The Java Event Models JDK (deprecated) JDK 1.1 and the new event model

Sample Applet: HideAndShow Visual objects text field with some text two buttons Actions performed hide button causes text field to disappear show button makes text field reappear

JDK What needs to be done init() method: create visual components and add them to the applet action(): determine which button was clicked and indicate associated action Problems nested if-statement in action() inefficient code associated with visual object far from its definition

Listeners and JDK 1.1 Listener responsible for processing UI events specifies actions that corresponds to an event JDK 1.1 code for listeners made explicit need to associate a listener for every visual object that the user interacts with listener should implement method(s) that specify corresponding actions

The Applet as the Listener Follows JDK event model What needs to be done init() method: as before but associate applet as listener for both buttons (addActionListener(this)) applet implements ActionListener interface define actionPerformed() instead of action() use e.getSource() instead of e.target to distinguish between buttons pressed Problems not addressed

“Third party” Listener Different listener for each button Listeners are separate objects Two different definitions of actionPerformed() No need to distinguish between buttons What needs to be done create listener objects add the objects as listeners for the buttons use anonymous classes

The Button as the Listener Create a new class (ActiveButton) class extends Button and implements ActionListener (contains actionPerformed()) actionPerformed() contains call to onClick() addActionListener(this) in constructor of class Applet instantiates ActiveButton onClick() or actionPerformed() is overridden as appropriate

Who should be the Listener? The applet no advantage except that old jdk1.0.2 code translates easily to this technique Third party clearly indicates the role of the listeners ActiveButton encapsulates listener-related activity applet code easier to read