Chap 7 - Inheritance. An example from Zoology. An example from java.lang. Other terms from inheritance. parent. Mammal. child. Mouse. child.

Size: px
Start display at page:

Download "Chap 7 - Inheritance. An example from Zoology. An example from java.lang. Other terms from inheritance. parent. Mammal. child. Mouse. child."

Transcription

1 Chap 7 - Inheritance An example from Zoology parent Mammal child child Mouse Elephant grandchild grandchild grandchild grandchild Field??? African Indian 1 2 An example from java.lang Other terms from inheritance Object Super class/type Number String Derived class Subtype Long Integer Double Float 3 4 //Person.java - characteristics common to all people class Person { Person(String name) { this.name = name; void setage(int age) { this.age = age; void setgender(char gender){ this.gender = gender; void setname(string name) { this.name = name; int getage() { return age; char getgender() { return gender; String getname() { return name; public String tostring() { return ("Name: " + name + ", Age: " + age + ", Gender: " + gender); private String name; private int age; private char gender; //male == M, female == F 5 //Student.java - an example subclass class Student extends Person { Student(String name) { super(name); void setcollege(string college) { this.college = college; void setgpa(double gpa) { this.gpa = gpa; void setyear(byte year) { this.year = year; String getcollege() { return college; double getgpa() { return gpa; byte getyear() { return year; public String tostring() { return(super.tostring() + "\n " + "College: " + college + ", GPA: " + gpa + ", Year: " + year); 6 1

2 static final byte FROSH = 1; static final byte SOPH = 2; static final byte JUNIOR = 3; static final byte SENIOR = 4; private String college = "Unknown"; private byte year; // FROSH, SOPH, private double gpa; //. to 4. //StudentTest.java class StudentTest { Student student = new Student("Jane Programmer"); student.setage(21); student.setgender( F ); student.setcollege("ucsc"); student.setyear(student.frosh); student.setgpa(3.75f); System.out.println(student.toString()); 7 8 Subtype Principle Methods defined in one class may be redefined in a subclass. This is called method overriding. A subclass object can always be used where an object of its superclass is expected. Treating a subclass object as a superclass object can only remove capabilities, not add them. With inheritance, new methods are Which tostring() gets called? class StudentTest { Student student = new Student("Jane Programmer"); student.setage(21); student.setgender( F ); student.setcollege("ucsc"); student.setyear(student.frosh); student.setgpa(3.75f); System.out.println(student.toString()); Person anyperson = studetn; System.out.println(anyPerson.toString()); added in the subclass, never taken away. 9 1 Can t use Student fields from Person reference class StudentTest { Student student = new Student("Jane Programmer"); student.setage(21); System.out.println(student.toString()); Person anyperson; if (Console.in.readInt() == 1) anyperson = student; else anyperson = new Person("John Doe"); anyperson.setyear(student.frosh); // illegal System.out.println(anyPerson.toString()); 11 Overriding vs Overloading Overloading is when you define two methods with the same name, in the same class, distinguished by their signatures. Overriding is when you redefine a method that has already been defined in a parent class (using the exact same signature). Overloading is resolved at compile time. Overriding is resolved at runtime (based on 12 the type of the implicit first parameter). 2

3 Dynamic Method Dispatch Determing at runtime, which overriden method to call, is called dynamic method dispatch. This is what allows println() to work with any object. tostring() is defined in Object (the parent of all classes). If you override tostring(), then inside of println(), a call to printthis.tostring(), will get to YOUR tostring(). 13 public class PrintWriter { public void println(object obj) { String s = obj.tostring(); // somehow get the string s printed 14 Dynamic Method Dispatch //SuperClass.java - a sample super class class SuperClass { public void print() { System.out.println( " inside SuperClass"); //SubClass.java - a subclass of SuperClass class SubClass extends SuperClass { public void print() { System.out.println( " inside SubClass"); 15 //TestInherit.java - overridden method selection. class TestInherit { SuperClass s = new SuperClass(); s.print(); s = new SubClass(); s.print(); 16 Access Modifiers, Method Overriding and the Subtype Principle Generic Methods When you override a method you cannot restrict access more than was done with the inherited method. Doing so would break the subtype principle. For example, if class Student overrode tostring() to be private, then System.out.println(anyPerson.toString()); would fail if anyperson was referring to a A generic method is a method that can operate on at least two different types of data. This is a form of polymorphism. println(object obj) is a generic method. It works for any Java reference type. In addition to tostring(), the class Object defines a method public boolean equals(object obj); Student

4 Method equals() in Object By overriding equals() we can write a generic methods that need to check if two objects are equal. //Count the number of times obj is found in array. static int howmanycopiesof(object obj, Object[] array) { int count = ; for (int i = ; i < array.length; i++) if (obj.equals(array[i])) count++; return count; 19 2 class EqualsTest { // Create and fill an array of Strings String[] stringarray = new String[1]; for (int i = ; i < stringarray.length; i++) stringarray[i] = "String " + i; // Create and fill an array of Counters Counter[] counterarray = new Counter[5]; for (int i = ; i < counterarray.length; i++) counterarray[i] = new Counter(); // Make two entries refer to the same Counter counterarray[2] = counterarray[]; When equals are not equal? Using the original Counter from chapter 6, the output of the previous program is 2 and 1. That's 2 Counters "equal" to counterarray[], and 1 String "equal" to "String 1". The class String, overrides equals() to compare the characters in two Strings. Counter uses the default equals() which just checks if the references point to the same System.out.println( howmanycopiesof(counterarray[], counterarray)); System.out.println( howmanycopiesof("string 1", stringarray)); 21 object. 22 counterarray[2] = counterarray[]; counterarray Counter objects Primitive Wrapper Classes Object Number Long Integer Double Float counterarray[2].equals(counterarray[]) is true

5 A Generic Numeric Method Abstract Classes static Number elementmin(number[] array) { Number min = array[]; for (int i = 1; i < array.length; i++) if (array[i].doublevalue() < min.doublevalue()) min = array[i]; return min; This works so long as the loss of precision in coverting to double doesn t affect the selected minimum. 25 An abstract class is use to derive other (concrete) classes. An abstract class usually provides some complete method definitions, but leaves some undefined, requiring all subclasses to provide definitions for the undefined methods. 26 abstract public class AbstractCounter { abstract public void click(); public int get() { return value; public void set(int x) { value = x; public String tostring() { return String.valueOf(value); protected int value; public class Counter extends AbstractCounter { public void click() { value = (value + 1) % 1; 27 public class CountByTwo extends AbstractCounter { public void click() { value = (value + 2) % 1; void samplemethod(abstractcounter counter) { counter.click(); You can declare variables/parameters of abstract types. You cannot ever actually create an object of an abstract class. E.g. new AbstractCounter() is illegal. 28 class Timer extends AbstractCounter { public Timer(int v) { set(v); public void click() { value++; seconds = value % 6; minutes = value / 6; public void set(int v) { value = v; seconds = v % 6; minutes = v / 6; public String tostring() { return minutes + " minutes, " + seconds + " seconds"; private int seconds, minutes; You can, of course, override any of the methods inherited from an abstract class. 29 Predator-Prey: An abstract class A simple simulation of an artificial ecology Object Living Fox Rabbit Grass 3 5

6 Pseudocode for Predator-Prey create two worlds, current and next initialize one with some life forms print the intial world for each step of the simulation update next based on current print the next world swith the roles of current and next 31 class PredatorPrey { World odd = new World(1), even = new World(1); int i, cycles = 1; even.eden(); //generate initial World System.out.println(even); //print initial state for (i = ; i < cycles; i++) { System.out.println("Cycle = " + i + "\n\n"); if (i % 2 == 1) { even.update(odd); System.out.println(even); else { odd.update(even); System.out.println(odd); 32 Counting Neighbors //Living.java - the superclass for all life forms abstract class Living { Life and death of life forms depends upon the number of various life forms in adjacent cells. Doing this counting is the same for all life forms so we will implement it in an abstract class, Living. Pseudocode set the count for all life form types to for each of the current cells 8 immediate neighbors if the neighbor is type LifeType abstract Count getcount(); abstract Living next(world world); abstract char tochar(); // character for this form void computeneighbors(world world) { world.clearneighborcounts(); world.cells[row][column].getcount().set(-1); for (int i = -1; i <= 1; i++) for (int j = -1; j <= 1; j++) world.cells[row+i][column+j].getcount().inc(); int row, column; //location then increment the count for LifeType class Fox extends Living { Fox(int r, int c, int a ) { row = r; column = c; age = a; Living next(world world) { computeneighbors(world); if (Fox.neighborCount.get() > 5 ) //too many Foxes return new Empty(row, column); else if (age > LIFE_EXPECTANCY) //Fox is too old return new Empty(row, column); else if (Rabbit.neighborCount.get() == ) return new Empty(row, column); // starved else return new Fox(row, column, age + 1); public String tostring(){ return "Fox age " + age; char tochar() { return F ; Count getcount() { return neighborcount; static Count neighborcount = new Count(); private int age; private final int LIFE_EXPECTANCY = 5;

7 Why must getcount() and neighborcount be repeated in each subclass of Living? Why not just move these definitions to Living? Answer: There is no way to write a method in Living, that accesses a static field in the subclasses of Living. We need a neighborcount for each of Fox, Rabbit, Grass, and Empty. class Rabbit extends Living { Rabbit(int r, int c, int a ) { row = r; column = c; age = a; Count getcount() { return neighborcount; Interfaces An interface in Java, is essentially an pure abstract class - all methods are abstract. An interface can contain only abstract methods, and constants. There are no instance variables. static Count neighborcount = new Count(); private int age; private final int LIFE_EXPECTANCY = 3; Suppose that different life forms have different notions of a neighborhood. Then in our simulation we can t provide computeneighbors() that works for all. We might just go with an interface instead of an abstract class. interface Living { Living next(world world); char tochar(); void computeneighbors(world world); Count getcount(); class Fox implements Living { // omitted methods/instance variables that are the // same as the earlier Fox class. public void computeneighbors(world world) { // each class must now define this method // an interface doesn t contain data fields // so row and column must be declared here // we can now make these members private private int row, column; 39 4 Multiple Inheritance What happens if a student is also a staff member? Person Multiple Inheritance What happens if a student is also a staff member? Person Student Faculty Staff Faculty Staff 41 Student 42 7

8 implements vs extends Java does not allow you to extend multiple classes. This avoids some problems related to multiple inheritance (e.g. what happens if you inherit a method from two different parent classes?). Java does allow you to implement multiple interfaces. Interfaces are about subtyping and polymorphism, whereas, inheriting methods interface Person { void setage(int age); void setgender(char gender); void setname(string name); int getage(); char getgender(); String getname(); is about code reuse interface Student extends Person { void setcollege(string college); void setgpa(double gpa); void setyear(byte year); String getcollege(); double getgpa(); byte getyear(); static final byte FROSH = 1; static final byte SOPH = 2; static final byte JUNIOR = 3; static final byte SENIOR = 4; import java.util.date; interface Staff extends Person { void setsalary(double salary); void setstartdate(date start); void setenddate(date end); void setssn(string ssn); double getsalary(); Date getstartdate(); Date getenddate(); String getssn(); import java.util.date; class StudentEmployee implements Student, Staff { // methods required by Person public void setage(int age){ public String getname(){ // methods required by Student public void setcollege(string college){ public byte getyear(){ // methods required by Staff public void setsalary(double salary){ public String getssn(){ 47 Can t instantiate an interface Just as with abstract classes, you can declare variables and parameters to be of an interface type, but you cannot create objects of an interface type. Using the declartions on the previous slides, new Staff() would be illegal. You could declare a variable or parameter to be of type Staff. This variable would always either be null or refer to an instance of some class that implements the interface 48 Staff. 8

9 instanceof if (x intanceof Shape) // x is a Shape, act accordingly else // x is not a Shape, act accordingly Person person = new Student(); if (person instanceof Student) { Student student = (Student)person; // operate on student 49 Illegal Cast Some illegal casts can be determined at compile time, others can only be detected at runtime. Trying to cast a Person into a String is a compile time error. The compiler knows that String is not a subclass of Person and hence the cast is always illegal. Trying to cast a Person into a Student, when the Person is not a Student, is a runtime error - even if YOU can see that this person couldn't possibly be a Student. 5 ClassCastException The following can only be detected at runtime, even though you can see it is clearly illegal. Person person = new Person(); Student student = (Student)person; // GenericArray.java - // demonstrate generic array container class GenericArray { Object[] array = new Object[4]; array[] = "String 1"; array[1] = new Integer(1); array[2] = "String 2"; array[3] = new Integer(2); for (int i = ; i < array.length; i++) { // see next slide for the body of the loop // end of for loop if (array[i] instanceof String) { String temp = (String)array[i]; System.out.println("Processing string " + temp); // do something appropriate for strings else if (array[i] instanceof Integer) { Integer temp = (Integer)array[i]; System.out.println("Processing Integer " + temp); // do something appropriate for an Integer else { System.out.println("Unexpected type " + array[i]); // do something to handle unexpected cases 53 9

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

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

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

java Features Version April 19, 2013 by Thorsten Kracht

java Features Version April 19, 2013 by Thorsten Kracht java Features Version April 19, 2013 by Thorsten Kracht Contents 1 Introduction 2 1.1 Hello World................................................ 2 2 Variables, Types 3 3 Input/Output 4 3.1 Standard I/O................................................

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

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

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

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

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

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

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

Introduction to Java. CS 3: Computer Programming in Java

Introduction to Java. CS 3: Computer Programming in Java Introduction to Java CS 3: Computer Programming in Java Objectives Begin with primitive data types Create a main class with helper methods Learn how to call built-in class methods and instance methods

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

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

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

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5 This Week CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5 School of Computer Science University of St Andrews Graham Kirby Alan Dearle More on Java classes Constructors Modifiers cdn.videogum.com/img/thumbnails/photos/commenter.jpg

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

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

Implementation Aspects of OO-Languages

Implementation Aspects of OO-Languages 1 Implementation Aspects of OO-Languages Allocation of space for data members: The space for data members is laid out the same way it is done for structures in C or other languages. Specifically: The data

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

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java

More information

C++ INTERVIEW QUESTIONS

C++ INTERVIEW QUESTIONS C++ INTERVIEW QUESTIONS http://www.tutorialspoint.com/cplusplus/cpp_interview_questions.htm Copyright tutorialspoint.com Dear readers, these C++ Interview Questions have been designed specially to get

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

Advanced Data Structures

Advanced Data Structures C++ Advanced Data Structures Chapter 8: Advanced C++ Topics Zhijiang Dong Dept. of Computer Science Middle Tennessee State University Chapter 8: Advanced C++ Topics C++ 1 C++ Syntax of 2 Chapter 8: Advanced

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

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

Two-Dimensional Arrays. Multi-dimensional Arrays. Two-Dimensional Array Indexing

Two-Dimensional Arrays. Multi-dimensional Arrays. Two-Dimensional Array Indexing Multi-dimensional Arrays The elements of an array can be any type Including an array type So int 2D[] []; declares an array of arrays of int Two dimensional arrays are useful for representing tables of

More information

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement? 1. Distinguish & and && operators. PART-A Questions 2. How does an enumerated statement differ from a typedef statement? 3. What are the various members of a class? 4. Who can access the protected members

More information

Part 3: GridWorld Classes and Interfaces

Part 3: GridWorld Classes and Interfaces GridWorld Case Study Part 3: GridWorld Classes and Interfaces In our example programs, a grid contains actors that are instances of classes that extend the Actor class. There are two classes that implement

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

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

Arrays in Java. Working with Arrays

Arrays in Java. Working with Arrays Arrays in Java So far we have talked about variables as a storage location for a single value of a particular data type. We can also define a variable in such a way that it can store multiple values. Such

More information

C++FA 5.1 PRACTICE MID-TERM EXAM

C++FA 5.1 PRACTICE MID-TERM EXAM C++FA 5.1 PRACTICE MID-TERM EXAM This practicemid-term exam covers sections C++FA 1.1 through C++FA 1.4 of C++ with Financial Applications by Ben Van Vliet, available at www.benvanvliet.net. 1.) A pointer

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

Programming Language Concepts: Lecture Notes

Programming Language Concepts: Lecture Notes Programming Language Concepts: Lecture Notes Madhavan Mukund Chennai Mathematical Institute 92 G N Chetty Road Chennai 600 017 http://www.cmi.ac.in/ madhavan 2 Contents I Object-oriented programming 7

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

CS170 Lab 11 Abstract Data Types & Objects

CS170 Lab 11 Abstract Data Types & Objects CS170 Lab 11 Abstract Data Types & Objects Introduction: Abstract Data Type (ADT) An abstract data type is commonly known as a class of objects An abstract data type in a program is used to represent (the

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

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be: Lecture 7 Picking Balls From an Urn The problem: An urn has n (n = 10) balls numbered from 0 to 9 A ball is selected at random, its' is number noted, it is set aside, and another ball is selected from

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

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

Compiling Object Oriented Languages. What is an Object-Oriented Programming Language? Implementation: Dynamic Binding

Compiling Object Oriented Languages. What is an Object-Oriented Programming Language? Implementation: Dynamic Binding Compiling Object Oriented Languages What is an Object-Oriented Programming Language? Last time Dynamic compilation Today Introduction to compiling object oriented languages What are the issues? Objects

More information

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class This homework is to be done individually. You may, of course, ask your fellow classmates for help if you have trouble editing files,

More information

Iteration CHAPTER 6. Topic Summary

Iteration CHAPTER 6. Topic Summary CHAPTER 6 Iteration TOPIC OUTLINE 6.1 while Loops 6.2 for Loops 6.3 Nested Loops 6.4 Off-by-1 Errors 6.5 Random Numbers and Simulations 6.6 Loop Invariants (AB only) Topic Summary 6.1 while Loops Many

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

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

Class 16: Function Parameters and Polymorphism

Class 16: Function Parameters and Polymorphism Class 16: Function Parameters and Polymorphism SI 413 - Programming Languages and Implementation Dr. Daniel S. Roche United States Naval Academy Fall 2011 Roche (USNA) SI413 - Class 16 Fall 2011 1 / 15

More information

Chapter 2: Elements of Java

Chapter 2: Elements of Java Chapter 2: Elements of Java Basic components of a Java program Primitive data types Arithmetic expressions Type casting. The String type (introduction) Basic I/O statements Importing packages. 1 Introduction

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

Java Basics: Data Types, Variables, and Loops

Java Basics: Data Types, Variables, and Loops Java Basics: Data Types, Variables, and Loops If debugging is the process of removing software bugs, then programming must be the process of putting them in. - Edsger Dijkstra Plan for the Day Variables

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

Description of Class Mutation Mutation Operators for Java

Description of Class Mutation Mutation Operators for Java Description of Class Mutation Mutation Operators for Java Yu-Seung Ma Electronics and Telecommunications Research Institute, Korea ysma@etri.re.kr Jeff Offutt Software Engineering George Mason University

More information

Basic Programming and PC Skills: Basic Programming and PC Skills:

Basic Programming and PC Skills: Basic Programming and PC Skills: Texas University Interscholastic League Contest Event: Computer Science The contest challenges high school students to gain an understanding of the significance of computation as well as the details of

More information

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go Debugging ESE112 Java Programming: API, Psuedo-Code, Scope It is highly unlikely that you will write code that will work on the first go Bugs or errors Syntax Fixable if you learn to read compiler error

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

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 Oct 4, 2013, p 1 Name: CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 1. (max 18) 4. (max 16) 2. (max 12) 5. (max 12) 3. (max 24) 6. (max 18) Total: (max 100)

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

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

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming 1 2 Foreword First of all, this book isn t really for dummies. I wrote it for myself and other kids who are on the team. Everything

More information

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For Projet Java Responsables: Ocan Sankur, Guillaume Scerri (LSV, ENS Cachan) Objectives - Apprendre à programmer en Java - Travailler à plusieurs sur un gros projet qui a plusieurs aspects: graphisme, interface

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

arrays C Programming Language - Arrays

arrays C Programming Language - Arrays arrays So far, we have been using only scalar variables scalar meaning a variable with a single value But many things require a set of related values coordinates or vectors require 3 (or 2, or 4, or more)

More information

Computer Programming I

Computer Programming I Computer Programming I COP 2210 Syllabus Spring Semester 2012 Instructor: Greg Shaw Office: ECS 313 (Engineering and Computer Science Bldg) Office Hours: Tuesday: 2:50 4:50, 7:45 8:30 Thursday: 2:50 4:50,

More information

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0 The following applies to all exams: Once exam vouchers are purchased you have up to one year from the date of purchase to use it. Each voucher is valid for one exam and may only be used at an Authorized

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

Smallest Java Package? Java.applet.* having 1 class and 3 interfaces. Applet Class and AppletContext, AppletStub, Audioclip interfaces.

Smallest Java Package? Java.applet.* having 1 class and 3 interfaces. Applet Class and AppletContext, AppletStub, Audioclip interfaces. OBJECTIVES OF JAVA Objects in java cannot contain other objects; they can only have references to other objects. Deletion of objects will be managed by Run time system. An Object can pass a message to

More information

Designing with Exceptions. CSE219, Computer Science III Stony Brook University http://www.cs.stonybrook.edu/~cse219

Designing with Exceptions. CSE219, Computer Science III Stony Brook University http://www.cs.stonybrook.edu/~cse219 Designing with Exceptions CSE219, Computer Science III Stony Brook University http://www.cs.stonybrook.edu/~cse219 Testing vs. Debugging Testing Coding Does the code work properly YES NO 2 Debugging Testing

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

Introduction to Data Structures

Introduction to Data Structures Introduction to Data Structures Albert Gural October 28, 2011 1 Introduction When trying to convert from an algorithm to the actual code, one important aspect to consider is how to store and manipulate

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

Java Programming Fundamentals

Java Programming Fundamentals Lecture 1 Part I Java Programming Fundamentals Topics in Quantitative Finance: Numerical Solutions of Partial Differential Equations Instructor: Iraj Kani Introduction to Java We start by making a few

More information

Programmation 2. Introduction à la programmation Java

Programmation 2. Introduction à la programmation Java Programmation 2 Introduction à la programmation Java 1 Course information CM: 6 x 2 hours TP: 6 x 2 hours CM: Alexandru Costan alexandru.costan at inria.fr TP: Vincent Laporte vincent.laporte at irisa.fr

More information

An Incomplete C++ Primer. University of Wyoming MA 5310

An Incomplete C++ Primer. University of Wyoming MA 5310 An Incomplete C++ Primer University of Wyoming MA 5310 Professor Craig C. Douglas http://www.mgnet.org/~douglas/classes/na-sc/notes/c++primer.pdf C++ is a legacy programming language, as is other languages

More information

Java Types and Enums. Nathaniel Osgood MIT 15.879. April 25, 2012

Java Types and Enums. Nathaniel Osgood MIT 15.879. April 25, 2012 Java Types and Enums Nathaniel Osgood MIT 15.879 April 25, 2012 Types in Java Types tell you the class of values from which a variable is drawn In Java we specify types for Parameters Variables Return

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

Variables, Constants, and Data Types

Variables, Constants, and Data Types Variables, Constants, and Data Types Primitive Data Types Variables, Initialization, and Assignment Constants Characters Strings Reading for this class: L&L, 2.1-2.3, App C 1 Primitive Data There are eight

More information

Java Cheatsheet. http://introcs.cs.princeton.edu/java/11cheatsheet/ Tim Coppieters Laure Philips Elisa Gonzalez Boix

Java Cheatsheet. http://introcs.cs.princeton.edu/java/11cheatsheet/ Tim Coppieters Laure Philips Elisa Gonzalez Boix Java Cheatsheet http://introcs.cs.princeton.edu/java/11cheatsheet/ Tim Coppieters Laure Philips Elisa Gonzalez Boix Hello World bestand genaamd HelloWorld.java naam klasse main methode public class HelloWorld

More information

public static void main(string[] args) { System.out.println("hello, world"); } }

public static void main(string[] args) { System.out.println(hello, world); } } Java in 21 minutes hello world basic data types classes & objects program structure constructors garbage collection I/O exceptions Strings Hello world import java.io.*; public class hello { public static

More information

15-214: Principles of Software Construction 8 th March 2012

15-214: Principles of Software Construction 8 th March 2012 15-214 Midterm Exam Andrew ID: SOLUTIONS 1 / 13 15-214: Principles of Software Construction 8 th March 2012 Name: SOLUTIONS Recitation Section (or Time): Instructions: Make sure that your exam is not missing

More information

Sources: On the Web: Slides will be available on:

Sources: On the Web: Slides will be available on: C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,

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

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

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program.

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program. Software Testing Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program. Testing can only reveal the presence of errors and not the

More information

Abstract Class & Java Interface

Abstract Class & Java Interface Abstract Class & Java Interface 1 Agenda What is an Abstract method and an Abstract class? What is Interface? Why Interface? Interface as a Type Interface vs. Class Defining an Interface Implementing an

More information

Habanero Extreme Scale Software Research Project

Habanero Extreme Scale Software Research Project Habanero Extreme Scale Software Research Project Comp215: Java Method Dispatch Zoran Budimlić (Rice University) Always remember that you are absolutely unique. Just like everyone else. - Margaret Mead

More information

Moving from CS 61A Scheme to CS 61B Java

Moving from CS 61A Scheme to CS 61B Java Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming Programming with Data Types to enhance reliability and productivity (through reuse and by facilitating evolution) Object (instance) State (fields) Behavior (methods) Identity

More information

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship. CSCI 253 Object Oriented Design: Java Review OOP George Blankenship George Blankenship 1 Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation Abstract Data Type (ADT) Implementation

More information

Part 1 Foundations of object orientation

Part 1 Foundations of object orientation OFWJ_C01.QXD 2/3/06 2:14 pm Page 1 Part 1 Foundations of object orientation OFWJ_C01.QXD 2/3/06 2:14 pm Page 2 1 OFWJ_C01.QXD 2/3/06 2:14 pm Page 3 CHAPTER 1 Objects and classes Main concepts discussed

More information

A Scala Tutorial for Java programmers

A Scala Tutorial for Java programmers A Scala Tutorial for Java programmers Version 1.3 January 16, 2014 Michel Schinz, Philipp Haller PROGRAMMING METHODS LABORATORY EPFL SWITZERLAND 2 1 Introduction This document gives a quick introduction

More information

Glossary of Object Oriented Terms

Glossary of Object Oriented Terms Appendix E Glossary of Object Oriented Terms abstract class: A class primarily intended to define an instance, but can not be instantiated without additional methods. abstract data type: An abstraction

More information

Introduction to Java Lecture Notes. Ryan Dougherty redoughe@asu.edu

Introduction to Java Lecture Notes. Ryan Dougherty redoughe@asu.edu 1 Introduction to Java Lecture Notes Ryan Dougherty redoughe@asu.edu Table of Contents 1 Versions....................................................................... 2 2 Introduction...................................................................

More information

Stack Allocation. Run-Time Data Structures. Static Structures

Stack Allocation. Run-Time Data Structures. Static Structures Run-Time Data Structures Stack Allocation Static Structures For static structures, a fixed address is used throughout execution. This is the oldest and simplest memory organization. In current compilers,

More information

Statements and Control Flow

Statements and Control Flow 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

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

Example of a Java program

Example of a Java program Example of a Java program class SomeNumbers static int square (int x) return x*x; public static void main (String[] args) int n=20; if (args.length > 0) // change default n = Integer.parseInt(args[0]);

More information