Construction of classes with classes

Size: px
Start display at page:

Download "Construction of classes with classes"

Transcription

1 (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.

2 (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

3 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 )

4 (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.

5 (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

6 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;

7 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 )

8 (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);

9 (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

10 (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

11 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 )

12 (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.

13 (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;

14 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 )

15 (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

16 (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!

17 (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 Graphical components: Component with subclasses Button, Checkbox, Container,... where e. g. Container has the subclasses Panel, Window 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)

18 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 )

19 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 )

20 (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... )

21 (November 13, 2014 Class hierarchies 21 ) Cont geometrical gures 1. Which classes are needed to represent the gures? Circle, Rectangle, 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?

22 (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

23 (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.

24 (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);

25 (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);

26 (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);

27 (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();

28 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 )

29 (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);

30 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 )

31 (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 circle rectangle circle

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

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

Yosemite National Park, California. CSE 114 Computer Science I Inheritance Yosemite National Park, California CSE 114 Computer Science I Inheritance Containment A class contains another class if it instantiates an object of that class HAS-A also called aggregation PairOfDice

More information

History OOP languages Year Language 1967 Simula-67 1983 Smalltalk

History OOP languages Year Language 1967 Simula-67 1983 Smalltalk History OOP languages Intro 1 Year Language reported dates vary for some languages... design Vs delievered 1957 Fortran High level programming language 1958 Lisp 1959 Cobol 1960 Algol Structured Programming

More information

Java Interview Questions and Answers

Java Interview Questions and Answers 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java

More information

The Interface Concept

The Interface Concept Multiple inheritance Interfaces Four often used Java interfaces Iterator Cloneable Serializable Comparable The Interface Concept OOP: The Interface Concept 1 Multiple Inheritance, Example Person name()

More information

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

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction INTRODUCTION TO COMPUTER PROGRAMMING Richard Pierse Class 7: Object-Oriented Programming Introduction One of the key issues in programming is the reusability of code. Suppose that you have written a program

More information

Chapter 2 Introduction to Java programming

Chapter 2 Introduction to Java programming Chapter 2 Introduction to Java programming 1 Keywords boolean if interface class true char else package volatile false byte final switch while throws float private case return native void protected break

More information

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

ATM Case Study OBJECTIVES. 2005 Pearson Education, Inc. All rights reserved. 2005 Pearson Education, Inc. All rights reserved. 1 ATM Case Study 2 OBJECTIVES.. 3 2 Requirements 2.9 (Optional) Software Engineering Case Study: Examining the Requirements Document 4 Object-oriented design (OOD) process using UML Chapters 3 to 8, 10

More information

Fundamentals of Java Programming

Fundamentals of Java Programming Fundamentals of Java Programming This document is exclusive property of Cisco Systems, Inc. Permission is granted to print and copy this document for non-commercial distribution and exclusive use by instructors

More information

Chapter 13 - Inheritance

Chapter 13 - Inheritance Goals Chapter 13 - Inheritance To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass constructors To learn about protected and package

More information

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

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin SE 360 Advances in Software Development Object Oriented Development in Java Polymorphism Dr. Senem Kumova Metin Modified lecture notes of Dr. Hüseyin Akcan Inheritance Object oriented programming languages

More information

D06 PROGRAMMING with JAVA

D06 PROGRAMMING with JAVA Cicles Formatius de Grau Superior Desenvolupament d Aplicacions Informàtiques D06 PROGRAMMING with JAVA Ch13 Inheritance PowerPoint presentation, created by Angel A. Juan - ajuanp(@)gmail.com, for accompanying

More information

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

Agenda. What is and Why Polymorphism? Examples of Polymorphism in Java programs 3 forms of Polymorphism Polymorphism 1 Agenda What is and Why Polymorphism? Examples of Polymorphism in Java programs 3 forms of Polymorphism 2 What is & Why Polymorphism? 3 What is Polymorphism? Generally, polymorphism refers

More information

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

CS 111 Classes I 1. Software Organization View to this point: CS 111 Classes I 1 Software Organization View to this point: Data Objects and primitive types Primitive types operators (+, /,,*, %). int, float, double, char, boolean Memory location holds the data Objects

More information

ICOM 4015: Advanced Programming

ICOM 4015: Advanced Programming ICOM 4015: Advanced Programming Lecture 10 Reading: Chapter Ten: Inheritance Copyright 2009 by John Wiley & Sons. All rights reserved. Chapter 10 Inheritance Chapter Goals To learn about inheritance To

More information

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

Practical Programming Methodology. Michael Buro. Class Inheritance (CMPUT-201) Practical Programming Methodology (CMPUT-201) Lecture 16 Michael Buro C++ Class Inheritance Assignments ctor, dtor, cctor, assignment op. and Inheritance Virtual Functions Class Inheritance Object Oriented

More information

Java Programming Language

Java Programming Language Lecture 1 Part II Java Programming Language Additional Features and Constructs Topics in Quantitative Finance: Numerical Solutions of Partial Differential Equations Instructor: Iraj Kani Subclasses and

More information

CS193j, Stanford Handout #10 OOP 3

CS193j, Stanford Handout #10 OOP 3 CS193j, Stanford Handout #10 Summer, 2003 Manu Kumar OOP 3 Abstract Superclass Factor Common Code Up Several related classes with overlapping code Factor common code up into a common superclass Examples

More information

Object-Oriented Programming: Polymorphism

Object-Oriented Programming: Polymorphism 1 10 Object-Oriented Programming: Polymorphism 10.3 Demonstrating Polymorphic Behavior 10.4 Abstract Classes and Methods 10.5 Case Study: Payroll System Using Polymorphism 10.6 final Methods and Classes

More information

Introduction: Abstract Data Types and Java Review

Introduction: Abstract Data Types and Java Review Introduction: Abstract Data Types and Java Review Computer Science E-119 Harvard Extension School Fall 2012 David G. Sullivan, Ph.D. Welcome to Computer Science E-119! We will study fundamental data structures.

More information

CSE 1020 Introduction to Computer Science I A sample nal exam

CSE 1020 Introduction to Computer Science I A sample nal exam 1 1 (8 marks) CSE 1020 Introduction to Computer Science I A sample nal exam For each of the following pairs of objects, determine whether they are related by aggregation or inheritance. Explain your answers.

More information

Java CPD (I) Frans Coenen Department of Computer Science

Java CPD (I) Frans Coenen Department of Computer Science Java CPD (I) Frans Coenen Department of Computer Science Content Session 1, 12:45-14:30 (First Java Programme, Inheritance, Arithmetic) Session 2, 14:45-16:45 (Input and Programme Constructs) Materials

More information

AP Computer Science Java Subset

AP Computer Science Java Subset APPENDIX A AP Computer Science Java Subset The AP Java subset is intended to outline the features of Java that may appear on the AP Computer Science A Exam. The AP Java subset is NOT intended as an overall

More information

Chapter 1 Java Program Design and Development

Chapter 1 Java Program Design and Development presentation slides for JAVA, JAVA, JAVA Object-Oriented Problem Solving Third Edition Ralph Morelli Ralph Walde Trinity College Hartford, CT published by Prentice Hall Java, Java, Java Object Oriented

More information

Using Inheritance and Polymorphism

Using Inheritance and Polymorphism 186 Chapter 16 Using Inheritance and Polymorphism In this chapter we make use of inheritance and polymorphism to build a useful data structure. 16.1 Abstract Classes Circle1a ( 16.1) is a variation of

More information

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

JAVA - INHERITANCE. extends is the keyword used to inherit the properties of a class. Below given is the syntax of extends keyword. http://www.tutorialspoint.com/java/java_inheritance.htm JAVA - INHERITANCE Copyright tutorialspoint.com Inheritance can be defined as the process where one class acquires the properties methodsandfields

More information

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

STATIC VARIABLE/ METHODS, INHERITANCE, INTERFACE AND COMMAND LINE ARGUMENTS STATIC VARIABLE/ METHODS, INHERITANCE, INTERFACE AND COMMAND LINE ARGUMENTS Example 1: Static Member Variable 1. /* 2. This Java Example shows how to declare and use static member variable inside a java

More information

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

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75 Preet raj Core Java and Databases CS4PR Time Allotted: 3 Hours Final Exam: Total Possible Points 75 Q1. What is difference between overloading and overriding? 10 points a) In overloading, there is a relationship

More information

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

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius Programming Concepts Practice Test 1 1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius 2) Consider the following statement: System.out.println("1

More information

Assignment # 2: Design Patterns and GUIs

Assignment # 2: Design Patterns and GUIs CSUS COLLEGE OF ENGINEERING AND COMPUTER SCIENCE Department of Computer Science CSc 133 Object-Oriented Computer Graphics Programming Spring 2014 John Clevenger Assignment # 2: Design Patterns and GUIs

More information

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

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013 Masters programmes in Computer Science and Information Systems Object-Oriented Design and Programming Sample module entry test xxth December 2013 This sample paper has more questions than the real paper

More information

Lösningsförslag till tentamen 121217

Lösningsförslag till tentamen 121217 Uppgift 1 Lösningsförslag till tentamen 121217 a) Utskriften blir: a = 5 och b = 10 a = 5 och b = 10 b) Utskriften blir 1 2 3 4 5 5 2 3 4 1 c) Utskriften blir 321 Uppgift 2 Med användning av dialogrutor:

More information

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

Lab 1A. Create a simple Java application using JBuilder. Part 1: make the simplest Java application Hello World 1. Start Jbuilder. 2. Lab 1A. Create a simple Java application using JBuilder In this lab exercise, we ll learn how to use a Java integrated development environment (IDE), Borland JBuilder 2005, to develop a simple Java application

More information

www.virtualians.pk CS506 Web Design and Development Solved Online Quiz No. 01 www.virtualians.pk

www.virtualians.pk CS506 Web Design and Development Solved Online Quiz No. 01 www.virtualians.pk CS506 Web Design and Development Solved Online Quiz No. 01 Which of the following is a general purpose container? JFrame Dialog JPanel JApplet Which of the following package needs to be import while handling

More information

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

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4 JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4 NOTE: SUN ONE Studio is almost identical with NetBeans. NetBeans is open source and can be downloaded from www.netbeans.org. I

More information

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

Contents. 9-1 Copyright (c) 1999-2004 N. Afshartous Contents 1. Introduction 2. Types and Variables 3. Statements and Control Flow 4. Reading Input 5. Classes and Objects 6. Arrays 7. Methods 8. Scope and Lifetime 9. Utility classes 10. Introduction to

More information

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

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 CRN:22430/21519 Pace University Spring 2006 CS122/504 Computer Programming II Instructor Lectures Office Hours Dr. Lixin Tao, [email protected], http://csis.pace.edu/~lixin Pleasantville Office: G320, (914)773-3449

More information

Block IQ. Marko Boon ([email protected]) Jacques Resing ([email protected])

Block IQ. Marko Boon (marko@win.tue.nl) Jacques Resing (resing@win.tue.nl) Block IQ Marko Boon ([email protected]) Jacques Resing ([email protected]) Part II: Object Oriented Programming 2/266 1. Objects and Classes 2. Class Inheritance and Interfaces 3. Some Predefined Java Classes

More information

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

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 The Java Type System By now, you have seen a fair amount of Java. Time to study in more depth the foundations of the language,

More information

Programming to Interfaces

Programming to Interfaces Chapter 9 Programming to Interfaces 9.1 Why We Need Specifications 9.2 Java Interfaces 9.2.1 Case Study: Databases 9.3 Inheritance 9.4 Reference Types, Subtypes, and instanceof 9.5 Abstract Classes 9.5.1

More information

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

J a v a Quiz (Unit 3, Test 0 Practice) Computer Science S-111a: Intensive Introduction to Computer Science Using Java Handout #11 Your Name Teaching Fellow J a v a Quiz (Unit 3, Test 0 Practice) Multiple-choice questions are worth 2 points

More information

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

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism Polymorphism Problems with switch statement Programmer may forget to test all possible cases in a switch. Tracking this down can be time consuming and error prone Solution - use virtual functions (polymorphism)

More information

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

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1 Exception Handling Error handling in general Java's exception handling mechanism The catch-or-specify priciple Checked and unchecked exceptions Exceptions impact/usage Overloaded methods Interfaces Inheritance

More information

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

Introduction to Programming System Design. CSCI 455x (4 Units) Introduction to Programming System Design CSCI 455x (4 Units) Description This course covers programming in Java and C++. Topics include review of basic programming concepts such as control structures,

More information

Sample CSE8A midterm Multiple Choice (circle one)

Sample CSE8A midterm Multiple Choice (circle one) Sample midterm Multiple Choice (circle one) (2 pts) Evaluate the following Boolean expressions and indicate whether short-circuiting happened during evaluation: Assume variables with the following names

More information

Week 1: Review of Java Programming Basics

Week 1: Review of Java Programming Basics Week 1: Review of Java Programming Basics Sources: Chapter 2 in Supplementary Book (Murach s Java Programming) Appendix A in Textbook (Carrano) Slide 1 Outline Objectives A simple Java Program Data-types

More information

Design and UML Class Diagrams

Design and UML Class Diagrams Design and UML Class Diagrams 1 Suggested reading: Practical UML: A hands on introduction for developers http://dn.codegear.com/article/31863 UML DistilledCh. 3, by M. Fowler How do people draw / write

More information

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

System.out.println(\nEnter Product Number 1-5 (0 to stop and view summary) : Benjamin Michael Java Homework 3 10/31/2012 1) Sales.java Code // Sales.java // Program calculates sales, based on an input of product // number and quantity sold import java.util.scanner; public class

More information

Basics of Java Programming Input and the Scanner class

Basics of Java Programming Input and the Scanner class Basics of Java Programming Input and the Scanner class CSC 1051 Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/

More information

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

Part I. Multiple Choice Questions (2 points each): Part I. Multiple Choice Questions (2 points each): 1. Which of the following is NOT a key component of object oriented programming? (a) Inheritance (b) Encapsulation (c) Polymorphism (d) Parallelism ******

More information

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

The following program is aiming to extract from a simple text file an analysis of the content such as: Text Analyser Aim The following program is aiming to extract from a simple text file an analysis of the content such as: Number of printable characters Number of white spaces Number of vowels Number of

More information

Software Engineering Techniques

Software Engineering Techniques Software Engineering Techniques Low level design issues for programming-in-the-large. Software Quality Design by contract Pre- and post conditions Class invariants Ten do Ten do nots Another type of summary

More information

Introducing Variance into the Java Programming Language DRAFT

Introducing Variance into the Java Programming Language DRAFT Introducing Variance into the Java Programming Language A Quick Tutorial DRAFT Christian Plesner Hansen Peter von der Ahé Erik Ernst Mads Torgersen Gilad Bracha June 3, 2003 1 Introduction Notice: This

More information

Pemrograman Dasar. Basic Elements Of Java

Pemrograman Dasar. Basic Elements Of Java Pemrograman Dasar Basic Elements Of Java Compiling and Running a Java Application 2 Portable Java Application 3 Java Platform Platform: hardware or software environment in which a program runs. Oracle

More information

Homework/Program #5 Solutions

Homework/Program #5 Solutions Homework/Program #5 Solutions Problem #1 (20 points) Using the standard Java Scanner class. Look at http://natch3z.blogspot.com/2008/11/read-text-file-using-javautilscanner.html as an exampleof using the

More information

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

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard INPUT & OUTPUT I/O Example Using keyboard input for characters import java.util.scanner; class Echo{ public static void main (String[] args) { Scanner sc = new Scanner(System.in); // scanner for the keyboard

More information

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq Introduction to Programming using Java wertyuiopasdfghjklzxcvbnmqwertyui

More information

Java Application Developer Certificate Program Competencies

Java Application Developer Certificate Program Competencies Java Application Developer Certificate Program Competencies After completing the following units, you will be able to: Basic Programming Logic Explain the steps involved in the program development cycle

More information

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

Introduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved. 1 2 Introduction to Java Applications 2.2 First Program in Java: Printing a Line of Text 2 Application Executes when you use the java command to launch the Java Virtual Machine (JVM) Sample program Displays

More information

Lecture J - Exceptions

Lecture J - Exceptions Lecture J - Exceptions Slide 1 of 107. Exceptions in Java Java uses the notion of exception for 3 related (but different) purposes: Errors: an internal Java implementation error was discovered E.g: out

More information

Introduction to Java Applets (Deitel chapter 3)

Introduction to Java Applets (Deitel chapter 3) Introduction to Java Applets (Deitel chapter 3) 1 2 Plan Introduction Sample Applets from the Java 2 Software Development Kit Simple Java Applet: Drawing a String Drawing Strings and Lines Adding Floating-Point

More information

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

Software Development with UML and Java 2 SDJ I2, Spring 2010 Software Development with UML and Java 2 SDJ I2, Spring 2010 Agenda week 7, 2010 Pakages Looking back Looking forward Packages Interfaces Page 1 Spring 2010 Download, Install/Setup 1. Java SE SDK (http://java.sun.com/javase/downloads)

More information

11 November 2015. www.isbe.tue.nl. www.isbe.tue.nl

11 November 2015. www.isbe.tue.nl. www.isbe.tue.nl UML Class Diagrams 11 November 2015 UML Class Diagrams The class diagram provides a static structure of all the classes that exist within the system. Classes are arranged in hierarchies sharing common

More information

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

Classes and Objects. Agenda. Quiz 7/1/2008. The Background of the Object-Oriented Approach. Class. Object. Package and import Classes and Objects 2 4 pm Tuesday 7/1/2008 @JD2211 1 Agenda The Background of the Object-Oriented Approach Class Object Package and import 2 Quiz Who was the oldest profession in the world? 1. Physician

More information

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

First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science First Java Programs V. Paúl Pauca Department of Computer Science Wake Forest University CSC 111D Fall, 2015 Hello World revisited / 8/23/15 The f i r s t o b l i g a t o r y Java program @author Paul Pauca

More information

Programming with Java GUI components

Programming with Java GUI components Programming with Java GUI components Java includes libraries to provide multi-platform support for Graphic User Interface objects. The multi-platform aspect of this is that you can write a program on a

More information

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

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following: In creating objects of the type, we have used statements similar to the following: f = new (); The parentheses in the expression () makes it look like a method, yet we never created such a method in our

More information

Introduction to Java

Introduction to Java Introduction to Java The HelloWorld program Primitive data types Assignment and arithmetic operations User input Conditional statements Looping Arrays CSA0011 Matthew Xuereb 2008 1 Java Overview A high

More information

LAB4 Making Classes and Objects

LAB4 Making Classes and Objects LAB4 Making Classes and Objects Objective The main objective of this lab is class creation, how its constructer creation, object creation and instantiation of objects. We will use the definition pane to

More information

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

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types Interfaces & Java Types Lecture 10 CS211 Fall 2005 Java Interfaces So far, we have mostly talked about interfaces informally, in the English sense of the word An interface describes how a client interacts

More information

Graduate Assessment Test (Sample)

Graduate Assessment Test (Sample) Graduate Assessment Test (Sample) CS201-203 1. Fibonacci sequence is defined by a recurrence relation. The series is: 0,1,1,2,3,5,8,13,... Write a complete recursive method/function that returns the fibonacci

More information

Object-Oriented Programming Lecture 2: Classes and Objects

Object-Oriented Programming Lecture 2: Classes and Objects Object-Oriented Programming Lecture 2: Classes and Objects Dr. Lê H!ng Ph"#ng -- Department of Mathematics, Mechanics and Informatics, VNUH July 2012 1 Content Class Object More on class Enum types Package

More information

Advanced OOP Concepts in Java

Advanced OOP Concepts in Java Advanced OOP Concepts in Java Michael B. Spring Department of Information Science and Telecommunications University of Pittsburgh [email protected] http://www.sis.pitt.edu/~spring 09/28/2001 1 Overview

More information

Web Development and Core Java Lab Manual V th Semester

Web Development and Core Java Lab Manual V th Semester Web Development and Core Java Lab Manual V th Semester DEPT. OF COMPUTER SCIENCE AND ENGINEERING Prepared By: Kuldeep Yadav Assistant Professor, Department of Computer Science and Engineering, RPS College

More information

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

How To Write A Program For The Web In Java (Java) 21 Applets and Web Programming As noted in Chapter 2, although Java is a general purpose programming language that can be used to create almost any type of computer program, much of the excitement surrounding

More information

Essentials of the Java Programming Language

Essentials of the Java Programming Language Essentials of the Java Programming Language A Hands-On Guide by Monica Pawlan 350 East Plumeria Drive San Jose, CA 95134 USA May 2013 Part Number TBD v1.0 Sun Microsystems. Inc. All rights reserved If

More information

An Introduction To UML Class Diagrams Classes

An Introduction To UML Class Diagrams Classes An Introduction To UML Class Diagrams Classes 1. Represent a user-created or defined data type a. they are an abstract data type (ADT) b. they implement data hiding and encapsulation c. they establish

More information

Twin A Design Pattern for Modeling Multiple Inheritance

Twin A Design Pattern for Modeling Multiple Inheritance Twin A Design Pattern for Modeling Multiple Inheritance Hanspeter Mössenböck University of Linz, Institute of Practical Computer Science, A-4040 Linz [email protected] Abstract. We introduce

More information

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

Grundlæggende Programmering IT-C, Forår 2001. Written exam in Introductory Programming Written exam in Introductory Programming IT University of Copenhagen, June 11, 2001 English version All materials are permitted during the exam, except computers. The exam questions must be answered in

More information

Inheritance, overloading and overriding

Inheritance, overloading and overriding Inheritance, overloading and overriding Recall with inheritance the behavior and data associated with the child classes are always an extension of the behavior and data associated with the parent class

More information

CMSC 202H. ArrayList, Multidimensional Arrays

CMSC 202H. ArrayList, Multidimensional Arrays CMSC 202H ArrayList, Multidimensional Arrays What s an Array List ArrayList is a class in the standard Java libraries that can hold any type of object an object that can grow and shrink while your program

More information

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

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 BSc (Hons) in Computer Applications, BSc (Hons) Computer Science with Network Security, BSc (Hons) Business Information Systems & BSc (Hons) Software Engineering Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT

More information

Java (12 Weeks) Introduction to Java Programming Language

Java (12 Weeks) Introduction to Java Programming Language Java (12 Weeks) Topic Lecture No. Introduction to Java Programming Language 1 An Introduction to Java o Java as a Programming Platform, The Java "White Paper" Buzzwords, Java and the Internet, A Short

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 5 Lecture 5-2: Random Numbers reading: 5.1-5.2 self-check: #8-17 exercises: #3-6, 10, 12 videos: Ch. 5 #1-2 1 The Random class A Random object generates pseudo-random* numbers.

More information

Teach Yourself Java in 21 Minutes

Teach Yourself Java in 21 Minutes Teach Yourself Java in 21 Minutes Department of Computer Science, Lund Institute of Technology Author: Patrik Persson Contact: [email protected] This is a brief tutorial in Java for you who already know another

More information

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

Short Introduction to the Concepts of Programming in Java Overview over the most important constructs Introduction to Java Short Introduction to the Concepts of Programming in Java Overview over the most important constructs OOIS 1998/99 Ulrike Steffens Software Systems Institute ul.steffens@tu- harburg.de

More information

(Eng. Hayam Reda Seireg) Sheet Java

(Eng. Hayam Reda Seireg) Sheet Java (Eng. Hayam Reda Seireg) Sheet Java 1. Write a program to compute the area and circumference of a rectangle 3 inche wide by 5 inches long. What changes must be made to the program so it works for a rectangle

More information

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

// Correntista. //Conta Corrente. package Banco; public class Correntista { String nome, sobrenome; int cpf; // Correntista public class Correntista { String nome, sobrenome; int cpf; public Correntista(){ nome = "zé"; sobrenome = "Pereira"; cpf = 123456; public void setnome(string n){ nome = n; public void setsobrenome(string

More information

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

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program Free Java textbook available online "Thinking in Java" by Bruce Eckel, 4th edition, 2006, ISBN 0131872486, Pearson Education Introduction to the Java programming language CS 4354 Summer II 2015 The third

More information

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

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1 The Java Series Java Essentials I What is Java? Basic Language Constructs Slide 1 What is Java? A general purpose Object Oriented programming language. Created by Sun Microsystems. It s a general purpose

More information

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

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program Free Java textbook available online "Thinking in Java" by Bruce Eckel, 4th edition, 2006, ISBN 0131872486, Pearson Education Introduction to the Java programming language CS 4354 Summer II 2014 Jill Seaman

More information

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

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language Translation Translating to Java Introduction to Computer Programming The job of a programmer is to translate a problem description into a computer language. You need to be able to convert a problem description

More information

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays. Arrays Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html 1 Grid in Assignment 2 How do you represent the state

More information

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

The Abstract Windowing Toolkit. Java Foundation Classes. Swing. In April 1997, JavaSoft announced the Java Foundation Classes (JFC). The Abstract Windowing Toolkit Since Java was first released, its user interface facilities have been a significant weakness The Abstract Windowing Toolkit (AWT) was part of the JDK form the beginning,

More information

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

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system. http://www.tutorialspoint.com/java/java_quick_guide.htm JAVA - QUICK GUIDE Copyright tutorialspoint.com What is Java? Java is: Object Oriented Platform independent: Simple Secure Architectural- neutral

More information

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

DC60 JAVA AND WEB PROGRAMMING JUNE 2014. b. Explain the meaning of the following statement public static void main (string args [ ] ) Q.2 a. How does Java differ from C and C++? Page 16 of Text Book 1 b. Explain the meaning of the following statement public static void main (string args [ ] ) Page 26 of Text Book 1 Q.3 a. What are the

More information

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

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. Exam Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) The JDK command to compile a class in the file Test.java is A) java Test.java B) java

More information