Construction of classes with classes



Similar documents
Yosemite National Park, California. CSE 114 Computer Science I Inheritance

History OOP languages Year Language 1967 Simula Smalltalk

Java Interview Questions and Answers

The Interface Concept

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

Chapter 2 Introduction to Java programming

ATM Case Study OBJECTIVES Pearson Education, Inc. All rights reserved Pearson Education, Inc. All rights reserved.

Fundamentals of Java Programming

Chapter 13 - Inheritance

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

D06 PROGRAMMING with JAVA

Agenda. What is and Why Polymorphism? Examples of Polymorphism in Java programs 3 forms of Polymorphism

CS 111 Classes I 1. Software Organization View to this point:

ICOM 4015: Advanced Programming

Practical Programming Methodology. Michael Buro. Class Inheritance (CMPUT-201)

Java Programming Language

CS193j, Stanford Handout #10 OOP 3

Object-Oriented Programming: Polymorphism

Introduction: Abstract Data Types and Java Review

CSE 1020 Introduction to Computer Science I A sample nal exam

Java CPD (I) Frans Coenen Department of Computer Science

AP Computer Science Java Subset

Chapter 1 Java Program Design and Development

Using Inheritance and Polymorphism

JAVA - INHERITANCE. extends is the keyword used to inherit the properties of a class. Below given is the syntax of extends keyword.

STATIC VARIABLE/ METHODS, INHERITANCE, INTERFACE AND COMMAND LINE ARGUMENTS

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Assignment # 2: Design Patterns and GUIs

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Lösningsförslag till tentamen

Lab 1A. Create a simple Java application using JBuilder. Part 1: make the simplest Java application Hello World 1. Start Jbuilder. 2.

CS506 Web Design and Development Solved Online Quiz No. 01

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Contents. 9-1 Copyright (c) N. Afshartous

PLV Goldstein 315, Tuesdays and Thursdays, 6:00PM-7:50PM. Tuesdays and Thursdays, 4:00PM-5:30PM and 7:50PM 9:30PM at PLV G320

Block IQ. Marko Boon Jacques Resing

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Programming to Interfaces

J a v a Quiz (Unit 3, Test 0 Practice)

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

Introduction to Programming System Design. CSCI 455x (4 Units)

Sample CSE8A midterm Multiple Choice (circle one)

Week 1: Review of Java Programming Basics

Design and UML Class Diagrams

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Basics of Java Programming Input and the Scanner class

Part I. Multiple Choice Questions (2 points each):

The following program is aiming to extract from a simple text file an analysis of the content such as:

Software Engineering Techniques

Introducing Variance into the Java Programming Language DRAFT

Pemrograman Dasar. Basic Elements Of Java

Homework/Program #5 Solutions

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Java Application Developer Certificate Program Competencies

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Lecture J - Exceptions

Introduction to Java Applets (Deitel chapter 3)

Software Development with UML and Java 2 SDJ I2, Spring 2010

11 November

Classes and Objects. Agenda. Quiz 7/1/2008. The Background of the Object-Oriented Approach. Class. Object. Package and import

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Programming with Java GUI components

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Introduction to Java

LAB4 Making Classes and Objects

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

Graduate Assessment Test (Sample)

Object-Oriented Programming Lecture 2: Classes and Objects

Advanced OOP Concepts in Java

Web Development and Core Java Lab Manual V th Semester

How To Write A Program For The Web In Java (Java)

Essentials of the Java Programming Language

An Introduction To UML Class Diagrams Classes

Twin A Design Pattern for Modeling Multiple Inheritance

Grundlæggende Programmering IT-C, Forår Written exam in Introductory Programming

Inheritance, overloading and overriding

CMSC 202H. ArrayList, Multidimensional Arrays

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

Java (12 Weeks) Introduction to Java Programming Language

Building Java Programs

Teach Yourself Java in 21 Minutes

Short Introduction to the Concepts of Programming in Java Overview over the most important constructs

(Eng. Hayam Reda Seireg) Sheet Java

// Correntista. //Conta Corrente. package Banco; public class Correntista { String nome, sobrenome; int cpf;

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

The Abstract Windowing Toolkit. Java Foundation Classes. Swing. In April 1997, JavaSoft announced the Java Foundation Classes (JFC).

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

DC60 JAVA AND WEB PROGRAMMING JUNE b. Explain the meaning of the following statement public static void main (string args [ ] )

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Transcription:

(November 13, 2014 Class hierarchies 1 ) Construction of classes with classes Classes can be built on existing classes through attributes of object types. Example: I A class PairOfDice can be constructed using two attributes of the type Dice. I A class CardDeck can be build with the help of an array of an object array containing 52 objects of the type Card I A class ListMap can be constructed with the help of ListNode objects I A class TrafficSystem can be constructed using objects from the classes Lane, Light, Vehicle... One use to say that this is a composition relation or a has relation.

(November 13, 2014 Class hierarchies 2 ) Class hierarchies A new class can also be built as a specialization of an existing class. Example: I The class StackException that is used in the Stack class is written as a sub class to Exception I If we have a class Vehicle, we can build new classes like Segway, Bicycle and Car. A Car can in turn be a base class for the classes Private car and Truck Vehicle Segway Bicycle Car Private Car Truck

In these cases you say that you have a class hierarchy I The class Vehicle is called a base class I The classes Segway, Bicycle and Car are derived classes or sub classes to the class Vehicle I A subclass (e. g. the class Car) can be used as a base class for other classes (e. g. Private car and Truck) One use to say the the phrase is a... that... can be used to identify when it is proper to use a class hierarchy. (November 13, 2014 Class hierarchies 3 )

(November 13, 2014 Class hierarchies 4 ) Inheritance An object of a sub class I has all the attributes and methods of the base class and I can add more by itself One say that the sub class inherits all the characteristics of the base class. Example: The class Car can have the attribute weight. A Private car can add npassenger while a Truck can add maxload. A subclass can also override methods and attributes in the baseclass.

(November 13, 2014 Class hierarchies 5 ) Unied Modeling Language (UML) The class hierarchies are often express in class diagrams in UML. Vehicle print() : void Segway Bicycle print() : void Car weight : double print() : void Private Car npassenger : int print() : void Truck maxload : double print() : void

public void print() { System.out.print("Car, weight " + weight); (November 13, 2014 Class hierarchies 6 ) The Vehicle hierarchy in code public class Vehicle { public void print() { System.out.print("Vehicle"); public class Segway extends Vehicle { public class Bicycle extends Vehicle { public void print() { System.out.print("Bicycle"); public class Car extends Vehicle { double weight; public Car( double v ) { weight = v;

Usage The code... public static void pr(string s) { System.out.print(s); public static void main(string [] args) { Vehicle f = new Vehicle(); Segway s = new Segway(); Bicycle c = new Bicycle(); Car b = new Car(1.2); pr("f: "); f.print(); pr("\n"); pr("s: "); s.print(); pr("\n"); pr("c: "); c.print(); pr("\n"); pr("b: "); b.print(); pr("\n");... give the printout f: Vehicle s: Vehicle c: Bicycle b: Car, weight 1.2 (November 13, 2014 Class hierarchies 7 )

(November 13, 2014 Class hierarchies 8 ) More subclasses public class PrivateCar extends Car { int npassenger = 5; public PrivateCar(double v) { super(v); public PrivateCar(double v, int ant) { super(v); npassenger = ant; public void print() { System.out.print("Private"); super.print(); System.out.print(", number of passengers " + npassenger);

(November 13, 2014 Class hierarchies 9 ) Continuation of main... PrivateCar pb1 = new PrivateCar(1.5); PrivateCar pb2 = new PrivateCar(0.9,4); pr("pb1: "); pb1.print(); pr("\n"); pr("weight b : " + b.weight + "\n"); pr("weight pb1: " + pb1.weight + "\n"); f = b; pr("f: "); f.print(); pr("\n"); f = pb1; pr("f: "); f.print(); pr("\n"); pb1 = (PrivateCar) f; pr("pb1: "); pb1.print(); pr("\n"); gives the printout pb1: PrivateCar, weight 1.5 and number of passengers 5 Weight b: 1.2 Weight pb1: 1.5 f: Car, weight 1.2 f: PrivateCar, weight 0.9 and number of passengers 4 pb1: PrivateCar, weight 0.9 and number of passengers 4

(November 13, 2014 Class hierarchies 10 ) Example of illegal operations pb1 = f; pb1 = (PrivateCar) c; pr("weight: " + f.weight); pb1 = (PrivateCar) f; // if f don't refer a PrivateCar The last can be made safe through if ( f instanceof PrivateCar ) pb1 = (PrivateCar) f; else... The operator instanceof should be used with caution

Conclusions If the class S is a subclass of the class B and if s is declared as a reference to S and b to B we have I An object of the class S has all attributes and methods that the class B have I If S declares an attribute that are declared B, that attribute is overridden by B's attribute. I A reference can refer objects of the declared class and its subclasses. I The construction b.x (or b.x()) requires that the attribute (or method) x is declared in B or any of B's baseclasses. I When you use an attribute a through dot notation p.a, it is the declaration of p that settles what attributes are used. I When you call a method m using p.m(), it is the type of the element that p refers that settles what method is selected. (so called dynamic or late binding). (November 13, 2014 Class hierarchies 11 )

(November 13, 2014 Class hierarchies 12 ) Methods that only are declared in selected classes Vehicle print() : void Segway Bicycle print() : void Car weight : double print() : void Private Car npassenger : int print() : void tax() : double Truck maxload : double print() : void tax() : double Cars are taxed, but the calculations are done in dierent way for private cars and trucks.

(November 13, 2014 Class hierarchies 13 ) Usage of the tax-method Car b = new Truck(3., 2.);... if (...) { b = new PrivateCar(1.2, 5);... double s; s = b.tax(); s = ((Truck) b).tax(); // Illegal! No tax in b // Risky! if ( b instanceof Truck ) // Works but clumsy s = ((Truck) b).tax(); // and inflexible else if ( b instanceof PrivateCar ) s = ((PrivateCar) b).tax(); else s = 0;

Better Dene also a method tax-method in the class Car or, better, in the class Vehicle: Vehicle print() : void tax() : double Segway Bicycle print() : void Car weight : double print() : void Private Car npassenger : int print() : void tax() : double Truck maxload : double print() : void tax() : double public class Vehicle { public void print() { System.out.print("Vehicle"); public double tax() { return 0; (November 13, 2014 Class hierarchies 14 )

(November 13, 2014 Class hierarchies 15 ) Levels of protection I private Only accessible from the classes own methods I public Accessible for all I protected Accessible from subclasses and classes in the same package I package If no level of protection is given. all classes are assigned package access level

(November 13, 2014 Class hierarchies 16 ) Constructors in inheritance Constructors are not inherited When an object of a subclass is created, the following steps are taken: 1. Instance variables take their default values 2. A constructor for the base class (super class) is called. You use the keyword super to specify which constructor in the base class that should be used. If super is not used, the parameterless constructor in the base class are used, in this case there has to exist such a constructor. 3. If there are initializarions they are evaluated and assigned to the respective attributes. 4. The statements in the constructor in the subclass are executed. Use super to avoid repeating code!

(November 13, 2014 Class hierarchies 17 ) Standard software in Java The Java environment is based on inheritance and class hierarchies! Example: 1. The classes for exceptions: Throwable with the subclasses Error and Exception with the subclasses... 2. Graphical components: Component with subclasses Button, Checkbox, Container,... where e. g. Container has the subclasses Panel, Window... 3. Maps: Map with (among others) the subclasss HashMap 4. The Collection classes: Collection with (among others) the subclass List that have the subclasses Vector and LinkedList (Map, Collection are List actually interfaces interface and not classes)

The Class Object The class Object is the baseclass to all classes. A reference to Object can thus refer any object. This can be used to construct general collection classes (lists, tables or... ): class ListNode { Object info; ListNode next; ListHead(Object i, ListNode n) { info = l; next = n; public class List { ListNode head; public void insertfirst(object o) { head = new ListNode(o, head)... (November 13, 2014 Class hierarchies 18 )

The class Object cont Some methods in the class Object: I Object clone() I boolean equals(object o) I String tostring() You often have reasons to override these! (November 13, 2014 Class hierarchies 19 )

(November 13, 2014 Class hierarchies 20 ) An example of using inheritance: geometrical gures Write a program that can handle pictures of circles, rectangles and other geometrical shapes. The program should be able to I represent a number of dierent shapes. I Draw an image of the represented shapes. I Compute the accumulated area of all gures. I Read rules about the structure of a certain shape. (other operations are of course possible: move, rotate, scale... )

(November 13, 2014 Class hierarchies 21 ) Cont geometrical gures 1. Which classes are needed to represent the gures? Circle, Rectangle,... 2. What attributes and methods should we have? I constructors I methods for calculating areas I methods for drawing 3. How should one represent a collection of such gures? I array? I list? I other structure? What type should be used for the elements in the structure?

(November 13, 2014 Class hierarchies 22 ) Cont geometrical gures Shape xcoord : int ycoord : int area() : double paint():void Circle radius: int area(): double paint():void Rectangle width : int height : int area() : double paint():void

(November 13, 2014 Class hierarchies 23 ) Cont geometrical gures Now we can e. g. do Shape[] fig = new Shape[100]; fig[0] = new Rectangle(...); fig[1] = new Circle(...);... (but we are to use a more exible structure than an array) There is no meningful implementation of area() and paint() in Shape! Declare these methods and the class Shape as abstract.

(November 13, 2014 Class hierarchies 24 ) Cont geometrical gures import java.awt.*; public abstract class Shape { protected int xcoord, ycoord; public Shape(int x, int y) { xcoord = x; ycoord = y; public abstract double area(); public abstract void paint(graphics g);

(November 13, 2014 Class hierarchies 25 ) Cont geometrical gures import java.awt.*; public class Circle extends Shape { protected int radius; public Circle(int x, int y, int r){ super(x,y); radius = r; public double area(){ return Math.PI*radius*radius; public void paint(graphics g){ g.setcolor(color.red); g.filloval(xcoord-radius, ycoord-radius, 2*radius, 2*radius);

(November 13, 2014 Class hierarchies 26 ) Cont geometrical gures import java.awt.*; public class Rectangle extends Shape { protected int width, height; public Rectangle(int x, int y, int w, int h) { super(x,y); width = w; height = h; public double area(){ return width*height; public void paint(graphics g){ g.setcolor(color.blue); g.fillrect(xcoord,ycoord,width,height);

(November 13, 2014 Class hierarchies 27 ) Cont geometrical gures To collect a number of dierent gures we use one of the collection classes in Java: LinkedList that is a (indirect) subclass to Collection (actually an interface). For this task, it is sucient to I Crete a LinkedList object: Collection<Shape> shapes = new LinkedList<Shape>(); I Add gures to the list, e. g.: shapes.add(new Circle(x,y,r)); I Iterate over the elements and access their methods. E. g: for (Shape s:shapes) s.paint();

Cont geometrical gures import javax.swing.*; import java.awt.*; import java.util.*; public class Drawing extends JPanel { private Collection<Shape> shapes; public Drawing(Collection<Shape> s, int w, int h) { shapes = s; setbackground(color.white); setpreferredsize(new Dimension(w,h)); public double area(){ double a = 0; for (Shape s:shapes) a += s.area(); return a; public void paintcomponent(graphics g){ super.paintcomponent(g); for (Shape s:shapes) s.paint(g); (November 13, 2014 Class hierarchies 28 )

(November 13, 2014 Class hierarchies 29 ) Cont geometrical gures import javax.swing.*; import java.awt.*; import java.util.*; public class DrawTest extends JFrame { public static void main(string[] args){ Collection<Shape> shapes = read(new Scanner(System.in)); Drawing d=new Drawing(shapes,400,400); System.out.println("Total area: " + (int)d.area()); new DrawTest(d); public DrawTest(Drawing d){ getcontentpane().add(d); pack(); settitle("drawtest"); setdefaultcloseoperation(exit_on_close); setvisible(true);

Cont geometrical gures private static Collection<Shape> read(scanner sc){ Collection<Shape> shapes = new LinkedList<Shape>(); while (sc.hasnext()){ String s=sc.next(); if (s.equals("circle")){ int x, y, r; x = sc.nextint(); y = sc.nextint(); r = sc.nextint(); shapes.add(new Circle(x,y,r)); else { int x, y, w, h; x = sc.nextint(); y = sc.nextint(); w = sc.nextint(); h = sc.nextint(); shapes.add(new Rectangle(x,y,w,h)); return shapes; (November 13, 2014 Class hierarchies 30 )

(November 13, 2014 Class hierarchies 31 ) Cont geometrical gures Note how the classes are based on inheritance. They inherit from the graphical classes in Java. Details in graphics are outside the scope of this course. If you run the program with java DrawTest < figure.txt and the le figure.txt contain rectangle 20 50 200 30 circle 350 100 30 rectangle 300 200 50 150 circle 100 300 80

Cont geometrical gures (November 13, 2014 Class hierarchies 32 )