Chapter 10. Further Abstraction Techniques

Size: px
Start display at page:

Download "Chapter 10. Further Abstraction Techniques"

Transcription

1 Chapter 10 Further Abstraction Techniques In the previous chapter, we saw how Java checks the usage of methods. We also saw that if the method is not defined in the superclass, the compiler will not work. There is a way to define the method in the superclass without really defining it. We can define an abstract method in the superclass. An abstract method does not have a body, and leave the implementation to the subclasses. If you think about the displaystudent() method, that we defined in the Student superclass: public void displaystudent() System.out.println("The name of the student is: " + name); if (studenttype.equals("gr")) System.out.println("The student is a Graduate student"); System.out.println("The student is an Undergraduate student"); // End of Display Student And the displaystudent( ) methods that we defined in the Graduate and Undergraduate subclasses: public void displaystudent() super.displaystudent(); boolean fin = true; for( int i=0; i < NUM_OF_TESTS; i++) int score = gettestscore(i); if (score == -1) fin = false; System.out.println("The score for test " + (i+1) + " is " + score); if (fin) computecoursegrade(); System.out.println("The course grade is " + getcoursegrade()); // End of displaystudent And public void displaystudent() super.displaystudent();

2 boolean fin = true; for( int i=0; i < NUM_OF_TESTS; i++) int score = gettestscore(i); if (score == -1) fin = false; System.out.println("The score for test " + (i+1) + " is " + score); if (fin) computecoursegrade(); System.out.println("The course grade is " + getcoursegrade()); // End of displaystudent With the new idea of abstract methods, they could be simplified. We define two abstract methods in the Student superclass: abstract public void displaystudent(); abstract public int getnumberoftests(); Then the two subclasses implement these two methods in the following way: In the Graduate subclass we will have: public void displaystudent() System.out.println("The name of the student is: " + getname()); System.out.println("The student is a Graduate student"); boolean fin = true; for( int i=0; i < NUM_OF_TESTS; i++) int score = gettestscore(i); if (score == -1) fin = false; System.out.println("The score for test " + (i+1) + " is " + score); if (fin) computecoursegrade(); System.out.println("The course grade is " + getcoursegrade()); // End of displaystudent And

3 public int getnumberoftests() return NUM_OF_TESTS; In the Undergraduate class, the implementation will be: public void displaystudent() System.out.println("The name of the student is: " + getname()); System.out.println("The student is an Undergraduate student"); boolean fin = true; for( int i=0; i < NUM_OF_TESTS; i++) int score = gettestscore(i); if (score == -1) fin = false; System.out.println("The score for test " + (i+1) + " is " + score); if (fin) computecoursegrade(); System.out.println("The course grade is " + getcoursegrade()); // End of displaystudent And public int getnumberoftests() return NUM_OF_TESTS; Note that the abstract method and the method that implements it on the subclasses should be such that all of them return the same type, and the type and number of arguments should also be the same. Also note that a class that has any abstract method can t be implemented, and we must define the class as an abstract class. We only will have instances of the subclasses. So our program for working with the students will look now like this: /** * Student is an abstract superclass that encloses both graduate and undergraduate students * A. Gutierrez */

4 public abstract class Student private String name; private int test[]; private String coursegrade; //constructor public Student(String studentname, int howmanytests) name = studentname; test = new int[howmanytests]; coursegrade = "*******"; // Setting a non valid grade on the student tests for(int i= 0; i < howmanytests ; i++) test[i] = -1; // accessors public String getcoursegrade() return coursegrade; public String getname() return name; public int gettestscore(int testnumber) return test[testnumber]; // mutators public void setname(string newname) name = newname; public void settestscore(int testnumber, int testscore) test[testnumber- 1] = testscore; public void setcoursegrade(string sgrade) coursegrade = sgrade; // Two new abstract methods abstract public void displaystudent();

5 abstract public int getnumberoftests(); // End Class Student /** * Undergraduate is a subclass that extends the Student class. Implements two abstract methods * A. Gutierrez */ import java.util.*; public class Undergraduate extends Student private static final int NUM_OF_TESTS = 3; private static Scanner myinputs = new Scanner(System.in); public Undergraduate(String sname) super(sname, NUM_OF_TESTS); public void computecoursegrade( ) int total = 0; for (int i = 0; i < NUM_OF_TESTS; i++) total += gettestscore(i); if (total/num_of_tests >= 70) setcoursegrade( "Pass"); setcoursegrade( "No Pass"); public void displaystudent() System.out.println("The name of the student is: " + getname()); System.out.println("The student is an Undergraduate student"); boolean fin = true; for( int i=0; i < NUM_OF_TESTS; i++) int score = gettestscore(i); if (score == -1) fin = false; System.out.println("The score for test " + (i+1) + " is " + score); if (fin) computecoursegrade();

6 System.out.println("The course grade is " + getcoursegrade()); // End of displaystudent public void settestscore(int testnumber, int testscore) String answer= ""; if (gettestscore(testnumber -1)!= -1) System.out.println("This student has already grade for this test"); System.out.println("Do you want to enter a new grade for test # "+ testnumber +"?"); System.out.println("Please enter y/n."); System.out.print(">"); answer = myinputs.nextline(); answer = new String(answer.trim().toUpperCase()); answer = "Y"; if (answer.equals("y")) super.settestscore(testnumber, testscore); // End of settestscore public int getnumberoftests() return NUM_OF_TESTS; // End of Undergraduate Class /** * Graduate is a subclass that extends the Student class. It implements two abstract methods * A. Gutierrez */ import java.util.*; public class Graduate extends Student private static final int NUM_OF_TESTS = 2; private static Scanner myinputs = new Scanner(System.in); public Graduate(String sname) super(sname, NUM_OF_TESTS); public void computecoursegrade( )

7 int total = 0; for (int i = 0; i < NUM_OF_TESTS; i++) total += gettestscore(i); if (total/num_of_tests >= 80) setcoursegrade( "Pass"); setcoursegrade( "No Pass"); public void displaystudent() System.out.println("The name of the student is: " + getname()); System.out.println("The student is a Graduate student"); boolean fin = true; for( int i=0; i < NUM_OF_TESTS; i++) int score = gettestscore(i); if (score == -1) fin = false; System.out.println("The score for test " + (i+1) + " is " + score); if (fin) computecoursegrade(); System.out.println("The course grade is " + getcoursegrade()); // End of displaystudent public void settestscore(int testnumber, int testscore) String answer= ""; if (gettestscore(testnumber -1)!= -1) System.out.println("This student has already grade for this test"); System.out.println("Do you want to enter a new grade for test # "+ testnumber +"?"); System.out.println("Please enter y/n."); System.out.print(">"); answer = myinputs.nextline(); answer = new String(answer.trim().toUpperCase()); answer = "Y"; if (answer.equals("y")) super.settestscore(testnumber, testscore); // End of settestscore public int getnumberoftests()

8 return NUM_OF_TESTS; // End of Graduate Class import java.util.*; /** * AllStudents is a collection of Student objects. * It uses the HashMap class, so be sure to import the java.util.hashmap, or * the java.util.* package * A. Gutierrez */ public class AllStudents // Storage for an arbitrary number of Undergraduate objects private HashMap<String, Student > alstudent; public Scanner myscanner = new Scanner(System.in); // Constructor public AllStudents () alstudent = new HashMap<String, Student >(); // Mutators public void storestudent(student nstudent) /* Check that the student is not already in the system, before inserting it into the * HashMap. */ // We could omit the checking because it was done in Working with students String name = nstudent.getname(); boolean exists = alstudent.containskey(name); if (exists) System.out.println("This student is already in the system"); alstudent.put(name, nstudent); // end of storestudent

9 public void modifystudent(student nstudent) String name = nstudent.getname(); alstudent.remove(name); alstudent.put(name, nstudent); // end of modifystudent public void removestudent(string studname) Student studenttodelete = alstudent.get(studname); System.out.println("Is the student " + studname +" the one you want to remove?"); System.out.println("Please enter y/n."); System.out.print(">"); //Gets the next String of data from the keyboard up to a "\n" and stores it in name String answer = myscanner.nextline(); // Convert the answer to upper case to establish a canonical form for the answer answer = new String(answer.trim().toUpperCase()); if (answer.equals("y")) alstudent.remove(studname); System.out.println("You should verify the student you want to remove"); // end of removesudent // Accessors // For the students public int numberofstudents() return alstudent.size(); public void showstudent(student nstudent) nstudent.displaystudent(); // End of showstudent public Student getstudent(string studname) boolean exists = alstudent.containskey(studname);

10 if (!exists) return null; // If the student is in the system, retrieve it. Student getstudent = alstudent.get(studname); return getstudent; // End of getstudent // End of AllStudents class /* WorkingWithStudents is a program to insert, remove, modify and display students in the system * They could be graduate or undergraduate students * A. Gutierrez */ import java.util.*; public class WorkingWithStudents private static Scanner myinputs = new Scanner(System.in); // Creating HashMap private static AllStudents unstudent = new AllStudents(); public static void main(string args[]) // Menu int choice = 0; String name = ""; String type = ""; Student studenttowork = null; while (choice!= 5) System.out.println("Choose the number for your option:"); System.out.println("To insert a student:...1"); System.out.println("To enter grades:...2"); System.out.println("To remove a student:...3");

11 System.out.println("To display a student:...4"); System.out.println("To finish:...5"); System.out.println("Please enter your choice."); System.out.print(">"); choice = myinputs.nextint(); myinputs.nextline(); if (choice <=4 && choice >= 1) name = getstudentname(); studenttowork= unstudent.getstudent(name); if (studenttowork == null) if (choice > 1) System.out.println("We could not find the student with name " + name); for(int i = 0; i < 64536; i++); choice = -1; type = getstudenttype(); if (choice == 1) System.out.println("This student is already in the system"); choice = -1 ; switch (choice) case 1: insertstudent(name, type); break; case 2: modifystudent(studenttowork); break; case 3: unstudent.removestudent(name); break; case 4: unstudent.showstudent(studenttowork); break; case 5: break; default: if (choice!= -1) System.out.print("Your choice should be a number between"); System.out.println(" 1 and 5. You entered " + choice); // End switch // End while // End main public static void insertstudent(string sname,string stype)

12 Student newstudent; if (stype.equals("gr")) newstudent = new Graduate(sName); newstudent = new Undergraduate(sName); unstudent.storestudent(newstudent); // end of insertstudent public static void modifystudent(student studenttomodify) String answer= ""; do int testchoice = 0; // Select the test to enter grades for System.out.println("Choose the number of the test you want to enter grades"); System.out.println("Please enter the number."); System.out.print(">"); testchoice = myinputs.nextint(); myinputs.nextline(); if ((testchoice > studenttomodify.getnumberoftests()) (testchoice < 1)) System.out.println("Wrong test number"); System.out.println("The number should be between 1 and " + studenttomodify.getnumberoftests()); System.out.println("You entered " + testchoice ); // Enter the grades for that test int ntestscore = 0; System.out.println("Enter the score for the test # "+ testchoice ); System.out.print(">"); ntestscore = myinputs.nextint(); myinputs.nextline(); studenttomodify.settestscore(testchoice, ntestscore); unstudent.modifystudent(studenttomodify); // Check if more grades want to be entered for this student System.out.println("Do you want to enter more grades for this student?"); System.out.println("Please enter y/n."); System.out.print(">"); answer = myinputs.nextline(); // Convert the answer to upper case to establish a canonical form for the answer

13 answer = new String(answer.trim().toUpperCase()); // end of do while (answer.equals("y")); // End of modifystudent public static String getstudentname() System.out.print("Enter the name of the student"); System.out.print(" you want to work with "); String name; do name = myinputs.nextline(); name = new String(name.trim().toUpperCase()); while (name.equals("")); return name; // End of getstudentname public static String getstudenttype() System.out.println("Enter the type of the student Graduate (GR) or Undergraduate (UG) "); System.out.println(" you want to work with. Please don't enter the brackets before and after"); System.out.print("> "); String type; do type = myinputs.nextline(); type = new String(type.trim().toUpperCase()); while (type.equals("") &&!type.equals("gr") &&!type.equals("ug")); return type; // End of getstudenttype // End of WorkingWithStudents Java does not allow extending more than one superclass. In other word, every class will have, at most, one superclass. But Java allows to define something besides an abstract class and a concrete class. We are talking about an interface, which is like a class, in which all the methods are abstract methods, and all the fields, if any, are public static and final. So instead of defining a class we define an interface. By just declaring that something is an interface, you don t have to explicitly define the fields as public,

14 static and final (it is understood), neither you have to specify that the methods are abstract methods (again, it is understood). A class can inherit from an interface in a similar way to the way it inherits from a class. But now we must use the word implements instead of extends. Contrary to the extension of superclasses, a class may implement several interfaces. It has to implement all the methods in them. The advantage of the interfaces is that allows different classes of objects (the classes that implement the interface) to be treated uniformly, allowing, at the same time, the existence of polymorphic variables and methods. Note that if a class extends another one and implement several interface, the extends part should always go in the definition of the class before the implements part(s). Example: public class Polar extends Component implements MouseListener, MouseMotionListener. It is clear from the heading of the class Polar that this class will serve as its own MouseListener and MouseMotionListener implementing the methods found in both interfaces. In our case the interface MouseListener is defined as: public interface MouseListener extends EventListener public void mouseclicked(mouseevent e); // Invoked when the mouse button has been clicked (pressed and released) on a component. public void void mousepressed(mouseevent e); // Invoked when a mouse button has been released on a component. public void void mouseentered(mouseevent e); // Invoked when the mouse enters a component. public void mousereleased(mouseevent e); // Invoked when a mouse button has been released on a component. public void mouseexited(mouseevent e); // Invoked when the mouse exits a component.

15 Note that the interface MouseListener extends the interface EventListener, that all event listener interfaces must extend.

Chapter 9. More about Inheritance

Chapter 9. More about Inheritance Chapter 9 More about Inheritance In the previous chapter, we saw how to use inheritance. Now we are going to look a little deeper into this concept. The first thing we need to consider is how Java checks

More information

Chapter 13. Inheritance and Polymorphism. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Chapter 13. Inheritance and Polymorphism. CS 180 Sunil Prabhakar Department of Computer Science Purdue University Chapter 13 Inheritance and Polymorphism CS 180 Sunil Prabhakar Department of Computer Science Purdue University Introduction Inheritance and polymorphism are key concepts of Object Oriented Programming.

More information

Announcements. Final exam. Course evaluations. Saturday Dec 15 10:20 am -- 12:20 pm Room: TBA

Announcements. Final exam. Course evaluations. Saturday Dec 15 10:20 am -- 12:20 pm Room: TBA Announcements Final exam Saturday Dec 15 10:20 am -- 12:20 pm Room: TBA Course evaluations Wednesday November 28th Need volunteer to collect evaluations and deliver them to LWSN. 1 Chapter 13 Inheritance

More information

Chapter 4. Inheritance

Chapter 4. Inheritance Chapter 4 Inheritance CSC 113 King Saud University College of Computer and Information Sciences Department of Computer Science Dr. S. HAMMAMI Objectives In In this this chapter you you will will learn

More information

Loops. CSE 114, Computer Science 1 Stony Brook University

Loops. CSE 114, Computer Science 1 Stony Brook University Loops CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation Suppose that you need to print a string (e.g., "Welcome to Java!") a user-defined times N: N?

More information

while (/* array size less than 1*/){ System.out.print("Number of students is invalid. Enter" + "number of students: "); /* read array size again */

while (/* array size less than 1*/){ System.out.print(Number of students is invalid. Enter + number of students: ); /* read array size again */ import java.util.scanner; public class CourseManager1 { public static void main(string[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter number of students: "); /* read the number

More information

JAVA MOCK TEST JAVA MOCK TEST II

JAVA MOCK TEST JAVA MOCK TEST II http://www.tutorialspoint.com JAVA MOCK TEST Copyright tutorialspoint.com This section presents you various set of Mock Tests related to Java Framework. You can download these sample mock tests at your

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Inheritance and Polymorphism Recitation 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University Project 5 Due Wed, Oct. 22 at 10 pm. All questions on the class newsgroup. Make use of lab

More information

Polymorphism. Chapter 4. CSC 113 King Saud University College of Computer and Information Sciences Department of Computer Science. Dr. S.

Polymorphism. Chapter 4. CSC 113 King Saud University College of Computer and Information Sciences Department of Computer Science. Dr. S. Chapter 4 Polymorphm CSC 113 King Saud University College Computer and Information Sciences Department Computer Science Objectives After you have read and studied th chapter, you should be able to Write

More information

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread G51PGP Programming Paradigms Lecture 008 Inner classes, anonymous classes, Swing worker thread 1 Reminder subtype polymorphism public class TestAnimals public static void main(string[] args) Animal[] animals

More information

Oct Decision Structures cont d

Oct Decision Structures cont d Oct. 29 - Decision Structures cont d Programming Style and the if Statement Even though an if statement usually spans more than one line, it is really one statement. For instance, the following if statements

More information

Example Program. public class ComputeArea {

Example Program. public class ComputeArea { COMMENTS While most people think of computer programs as a tool for telling computers what to do, programs are actually much more than that. Computer programs are written in human readable language for

More information

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

Lesson 7 Part 2 Flags

Lesson 7 Part 2 Flags Lesson 7 Part 2 Flags A Flag is a boolean variable that signals when some condition exists in a program. When a flag is set to true, it means some condition exists When a flag is set to false, it means

More information

ECE 462 Object-Oriented Programming using C++ and Java. Key Inputs in Java Games

ECE 462 Object-Oriented Programming using C++ and Java. Key Inputs in Java Games ECE 462 Object-Oriented Programming g using C++ and Java Key Inputs in Java Games Yung-Hsiang Lu yunglu@purdue.edu d YHL Java Key Input 1 Handle Key Events have the focus of the keyboard inputs by calling

More information

Class, Variable, Constructor, Object, Method Questions

Class, Variable, Constructor, Object, Method Questions Class, Variable, Constructor, Object, Method Questions http://www.wideskills.com/java-interview-questions/java-classes-andobjects-interview-questions https://www.careerride.com/java-objects-classes-methods.aspx

More information

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them. Dec. 9 Loops Please answer the following questions. Do not re-code the enclosed codes if you have already completed them. What is a loop? What are the three loops in Java? What do control structures do?

More information

Chapter 5 Lab Methods

Chapter 5 Lab Methods Chapter 5 Lab Methods Lab Objectives Be able to write methods Be able to call methods Be able to write javadoc comments Be able to create HTML documentation using the javadoc utility Introduction Methods

More information

CSIS 10A Practice Final Exam Solutions

CSIS 10A Practice Final Exam Solutions CSIS 10A Practice Final Exam Solutions 1) (5 points) What would be the output when the following code block executes? int a=3, b=8, c=2; if (a < b && b < c) b = b + 2; if ( b > 5 a < 3) a = a 1; if ( c!=

More information

Web-CAT submission URL: CAT.woa/wa/assignments/eclipse

Web-CAT submission URL:  CAT.woa/wa/assignments/eclipse King Saud University College of Computer & Information Science CSC111 Lab10 Arrays II All Sections ------------------------------------------------------------------- Instructions Web-CAT submission URL:

More information

Objects as a programming concept

Objects as a programming concept Objects as a programming concept IB Computer Science Content developed by Dartford Grammar School Computer Science Department HL Topics 1-7, D1-4 1: System design 2: Computer Organisation 3: Networks 4:

More information

CS212 Midterm. 1. Read the following code fragments and answer the questions.

CS212 Midterm. 1. Read the following code fragments and answer the questions. CS1 Midterm 1. Read the following code fragments and answer the questions. (a) public void displayabsx(int x) { if (x > 0) { System.out.println(x); return; else { System.out.println(-x); return; System.out.println("Done");

More information

ENCAPSULATION AND POLYMORPHISM

ENCAPSULATION AND POLYMORPHISM MODULE 3 ENCAPSULATION AND POLYMORPHISM Objectives > After completing this lesson, you should be able to do the following: Use encapsulation in Java class design Model business problems using Java classes

More information

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007 Name: Please fill in your Student Number and Name. Student Number : Student Number: University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ 2007 Final Examination Question Max

More information

Instance Method Development Demo

Instance Method Development Demo Instance Method Development Demo Write a class Person with a constructor that accepts a name and an age as its argument. These values should be stored in the private attributes name and age. Then, write

More information

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

Software and Programming 1

Software and Programming 1 Software and Programming 1 Week 9 Lab - Use of Classes and Inheritance 8th March 2018 SP1-Lab9-2018.ppt Tobi Brodie (Tobi@dcs.bbk.ac.uk) 1 Lab 9: Objectives Exercise 1 Student & StudentTest classes 1.

More information

Programming Language Concepts: Lecture 2

Programming Language Concepts: Lecture 2 Programming Language Concepts: Lecture 2 Madhavan Mukund Chennai Mathematical Institute madhavan@cmi.ac.in http://www.cmi.ac.in/~madhavan/courses/pl2009 PLC 2009, Lecture 2, 19 January 2009 Classes and

More information

CAT.woa/wa/assignments/eclipse

CAT.woa/wa/assignments/eclipse King Saud University College of Computer & Information Science CSC111 Lab10 Arrays II All Sections ------------------------------------------------------------------- Instructions Web-CAT submission URL:

More information

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch Problem Solving Creating a class from scratch 1 Recipe for Writing a Class 1. Write the class boilerplate stuff 2. Declare Fields 3. Write Creator(s) 4. Write accessor methods 5. Write mutator methods

More information

Object Oriented Programming. Java-Lecture 6 - Arrays

Object Oriented Programming. Java-Lecture 6 - Arrays Object Oriented Programming Java-Lecture 6 - Arrays Arrays Arrays are data structures consisting of related data items of the same type In Java arrays are objects -> they are considered reference types

More information

Java for Non Majors Spring 2018

Java for Non Majors Spring 2018 Java for Non Majors Spring 2018 Final Study Guide The test consists of 1. Multiple choice questions - 15 x 2 = 30 points 2. Given code, find the output - 3 x 5 = 15 points 3. Short answer questions - 3

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 03: Creating Classes MOUNA KACEM mouna@cs.wisc.edu Spring 2019 Creating Classes 2 Constructors and Object Initialization Static versus non-static fields/methods Encapsulation

More information

Chapter 4 Defining Classes I

Chapter 4 Defining Classes I Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the

More information

Lecture 14. 'for' loops and Arrays

Lecture 14. 'for' loops and Arrays Lecture 14 'for' loops and Arrays For Loops for (initiating statement; conditional statement; next statement) // usually incremental body statement(s); The for statement provides a compact way to iterate

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 03: Creating Classes MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Creating Classes 2 Constructors and Object Initialization Static versus non-static fields/methods Encapsulation

More information

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017 Programming Language Concepts Object-Oriented Programming Janyl Jumadinova 28 February, 2017 Three Properties of Object-Oriented Languages: Encapsulation Inheritance Dynamic method binding (polymorphism)

More information

Class Hierarchy and Interfaces. David Greenstein Monta Vista High School

Class Hierarchy and Interfaces. David Greenstein Monta Vista High School Class Hierarchy and Interfaces David Greenstein Monta Vista High School Inheritance Inheritance represents the IS-A relationship between objects. an object of a subclass IS-A(n) object of the superclass

More information

The action of the program depends on the input We can create this program using an if statement

The action of the program depends on the input We can create this program using an if statement The program asks the user to enter a number If the user enters a number greater than zero, the program displays a message: You entered a number greater than zero Otherwise, the program does nothing The

More information

Write a program which converts all lowercase letter in a sentence to uppercase.

Write a program which converts all lowercase letter in a sentence to uppercase. Write a program which converts all lowercase letter in a sentence to uppercase. For Example: 1) Consider a sentence "welcome to Java Programming!" its uppercase conversion is " WELCOME TO JAVA PROGRAMMING!"

More information

Programming with Java

Programming with Java Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

More information

Introduction to Algorithms and Data Structures

Introduction to Algorithms and Data Structures Introduction to Algorithms and Data Structures Lecture 4 Structuring Data: Multidimensional Arrays, Arrays of Objects, and Objects Containing Arrays Grouping Data We don t buy individual eggs; we buy them

More information

Over and Over Again GEEN163

Over and Over Again GEEN163 Over and Over Again GEEN163 There is no harm in repeating a good thing. Plato Homework A programming assignment has been posted on Blackboard You have to convert three flowcharts into programs Upload the

More information

Practice Problems: Instance methods

Practice Problems: Instance methods Practice Problems: Instance methods Submit your java files to D2L. Late work will not be acceptable. a. Write a class Person with a constructor that accepts a name and an age as its argument. These values

More information

Computer Programming, I. Laboratory Manual. Final Exam Solution

Computer Programming, I. Laboratory Manual. Final Exam Solution Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Final Exam Solution

More information

Lab1 Solution. Lab2 Solution. MathTrick.java. CoinFlip.java

Lab1 Solution. Lab2 Solution. MathTrick.java. CoinFlip.java Lab1 Solution MathTrick.java /** * MathTrick Lab 1 * * @version 8/25/11 * Completion time: 10-15 minutes public class MathTrick public static void main(string [] args) int num = 34; //Get a positive integer

More information

L4,5: Java Overview II

L4,5: Java Overview II L4,5: Java Overview II 1. METHODS Methods are defined within classes. Every method has an associated class; in other words, methods are defined only within classes, not standalone. Methods are usually

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

Chapter 14 Abstract Classes and Interfaces

Chapter 14 Abstract Classes and Interfaces Chapter 14 Abstract Classes and Interfaces 1 What is abstract class? Abstract class is just like other class, but it marks with abstract keyword. In abstract class, methods that we want to be overridden

More information

Announcement. Agenda 7/31/2008. Polymorphism, Dynamic Binding and Interface. The class will continue on Tuesday, 12 th August

Announcement. Agenda 7/31/2008. Polymorphism, Dynamic Binding and Interface. The class will continue on Tuesday, 12 th August Polymorphism, Dynamic Binding and Interface 2 4 pm Thursday 7/31/2008 @JD2211 1 Announcement Next week is off The class will continue on Tuesday, 12 th August 2 Agenda Review Inheritance Abstract Array

More information

Fundamentals of Programming Data Types & Methods

Fundamentals of Programming Data Types & Methods Fundamentals of Programming Data Types & Methods By Budditha Hettige Overview Summary (Previous Lesson) Java Data types Default values Variables Input data from keyboard Display results Methods Operators

More information

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette COMP 250: Java Programming I Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette Variables and types [Downey Ch 2] Variable: temporary storage location in memory.

More information

Assignment 8B SOLUTIONS

Assignment 8B SOLUTIONS CSIS 10A Assignment 8B SOLUTIONS Read: Chapter 8 Choose and complete any 10 points from the problems below, which are all included in the download file on the website. Use BlueJ to complete the assignment,

More information

The Java language has a wide variety of modifiers, including the following:

The Java language has a wide variety of modifiers, including the following: PART 5 5. Modifier Types The Java language has a wide variety of modifiers, including the following: Java Access Modifiers Non Access Modifiers 5.1 Access Control Modifiers Java provides a number of access

More information

Object Oriented Relationships

Object Oriented Relationships Lecture 3 Object Oriented Relationships Group home page: http://groups.yahoo.com/group/java CS244/ 2 Object Oriented Relationships Object oriented programs usually consisted of a number of classes Only

More information

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Computer Programming Lab (ECOM 2114) ABSTRACT In this Lab you will learn to define and invoke void and return java methods JAVA

More information

CH. 2 OBJECT-ORIENTED PROGRAMMING

CH. 2 OBJECT-ORIENTED PROGRAMMING CH. 2 OBJECT-ORIENTED PROGRAMMING ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016) OBJECT-ORIENTED

More information

Loops. GEEN163 Introduction to Computer Programming

Loops. GEEN163 Introduction to Computer Programming Loops GEEN163 Introduction to Computer Programming Simplicity is prerequisite for reliability. Edsger W. Dijkstra Programming Assignment A new programming assignment has been posted on Blackboard for this

More information

CSIS 10A PRACTICE FINAL EXAM Name Closed Book Closed Computer 3 Sheets of Notes Allowed

CSIS 10A PRACTICE FINAL EXAM Name Closed Book Closed Computer 3 Sheets of Notes Allowed CSIS 10A PRACTICE FINAL EXAM Name Closed Book Closed Computer 3 Sheets of Notes Allowed MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) What would

More information

F I N A L E X A M I N A T I O N

F I N A L E X A M I N A T I O N Faculty Of Computer Studies M257 Putting Java to Work F I N A L E X A M I N A T I O N Number of Exam Pages: (including this cover sheet( Spring 2011 April 4, 2011 ( 5 ) Time Allowed: ( 1.5 ) Hours Student

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 5 Lecture 5-4: do/while loops, assertions reading: 5.1, 5.5 1 The do/while loop do/while loop: Performs its test at the end of each repetition. Guarantees that the loop's

More information

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1 Name SOLUTION Page Points Score 2 15 3 8 4 18 5 10 6 7 7 7 8 14 9 11 10 10 Total 100 1 P age 1. Program Traces (41 points, 50 minutes)

More information

Object Oriented Programming. Java-Lecture 1

Object Oriented Programming. Java-Lecture 1 Object Oriented Programming Java-Lecture 1 Standard output System.out is known as the standard output object Methods to display text onto the standard output System.out.print prints text onto the screen

More information

Repetition, Looping. While Loop

Repetition, Looping. While Loop Repetition, Looping Last time we looked at how to use if-then statements to control the flow of a program. In this section we will look at different ways to repeat blocks of statements. Such repetitions

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. CSIS 10A PRACTICE FINAL EXAM SOLUTIONS Closed Book Closed Computer 3 Sheets of Notes Allowed MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) What

More information

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

! definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. ! We often use language like Indefinite loops while loop! indefinite loop: A loop where it is not obvious in advance how many times it will execute.! We often use language like " "Keep looping as long as or while this condition is

More information

Tutorial 12. Exercise 1: Exercise 2: CSC111 Computer Programming I

Tutorial 12. Exercise 1: Exercise 2: CSC111 Computer Programming I College of Computer and Information Sciences CSC111 Computer Programming I Exercise 1: Tutorial 12 Arrays: A. Write a method add that receives an array of integers arr, the number of the elements in the

More information

CMSC 132: Object-Oriented Programming II. Inheritance

CMSC 132: Object-Oriented Programming II. Inheritance CMSC 132: Object-Oriented Programming II Inheritance 1 Mustang vs Model T Ford Mustang Ford Model T 2 Interior: Mustang vs Model T 3 Frame: Mustang vs Model T Mustang Model T 4 Compaq: old and new Price:

More information

Practice for Chapter 11

Practice for Chapter 11 Practice for Chapter 11 MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) Object-oriented programming allows you to derive new classes from existing

More information

More About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario

More About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario More About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario The Story So Far... Classes as collections of fields and methods. Methods can access fields, and

More information

Chapter 3. Selections

Chapter 3. Selections Chapter 3 Selections 1 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator 6. The Switch Statement 7. Useful Hints 2 1. Flow of

More information

Chapter 5 Lab Methods

Chapter 5 Lab Methods Chapter 5 Lab Methods Lab Objectives Be able to write methods Be able to call methods Be able to write javadoc comments Be able to create HTML documentation for our Java class using javadoc Introduction

More information

STUDENT LESSON A12 Iterations

STUDENT LESSON A12 Iterations STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of

More information

Distributed Systems Recitation 1. Tamim Jabban

Distributed Systems Recitation 1. Tamim Jabban 15-440 Distributed Systems Recitation 1 Tamim Jabban Office Hours Office 1004 Tuesday: 9:30-11:59 AM Thursday: 10:30-11:59 AM Appointment: send an e-mail Open door policy Java: Object Oriented Programming

More information

Goals for Today. CSE1030 Introduction to Computer Science II. CSE1030 Lecture #9. Review is-a versus has-a. Lecture #9 Inheritance I

Goals for Today. CSE1030 Introduction to Computer Science II. CSE1030 Lecture #9. Review is-a versus has-a. Lecture #9 Inheritance I CSE1030 Introduction to Computer Science II Lecture #9 Inheritance I Goals for Today Today we start discussing Inheritance (continued next lecture too) This is an important fundamental feature of Object

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 5 Random Numbers reading: 5.1, 5.6 1 http://xkcd.com/221/ 2 The while loop while loop: Repeatedly executes its body as long as a logical test is true. while (test) { statement(s);

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 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

More information

Abstract Classes and Interfaces

Abstract Classes and Interfaces Abstract Classes and Interfaces Reading: Reges and Stepp: 9.5 9.6 CSC216: Programming Concepts Sarah Heckman 1 Abstract Classes A Java class that cannot be instantiated, but instead serves as a superclass

More information

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018 Birkbeck (University of London) Software and Programming 1 In-class Test 2.1 22 Mar 2018 Student Name Student Number Answer ALL Questions 1. What output is produced when the following Java program fragment

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 5 Lecture 5-4: do/while loops, assertions reading: 5.1, 5.5 1 The do/while loop do/while loop: Performs its test at the end of each repetition. Guarantees that the loop's

More information

Conditional Execution

Conditional Execution Unit 3, Part 3 Conditional Execution Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Review: Simple Conditional Execution in Java if () { else {

More information

CSCI 355 Lab #2 Spring 2007

CSCI 355 Lab #2 Spring 2007 CSCI 355 Lab #2 Spring 2007 More Java Objectives: 1. To explore several Unix commands for displaying information about processes. 2. To explore some differences between Java and C++. 3. To write Java applications

More information

Midterm Examination (MTA)

Midterm Examination (MTA) M105: Introduction to Programming with Java Midterm Examination (MTA) Spring 2013 / 2014 Question One: [6 marks] Choose the correct answer and write it on the external answer booklet. 1. Compilers and

More information

Java Fundamentals (II)

Java Fundamentals (II) Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class

More information

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and Classes CS 251 Intermediate Programming Methods and Classes Brooke Chenoweth University of New Mexico Fall 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

Lecture 8 " INPUT " Instructor: Craig Duckett

Lecture 8  INPUT  Instructor: Craig Duckett Lecture 8 " INPUT " Instructor: Craig Duckett Assignments Assignment 2 Due TONIGHT Lecture 8 Assignment 1 Revision due Lecture 10 Assignment 2 Revision Due Lecture 12 We'll Have a closer look at Assignment

More information

CS 251 Intermediate Programming Methods and More

CS 251 Intermediate Programming Methods and More CS 251 Intermediate Programming Methods and More Brooke Chenoweth University of New Mexico Spring 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

Birkbeck (University of London) Software and Programming 1 In-class Test Mar Answer ALL Questions

Birkbeck (University of London) Software and Programming 1 In-class Test Mar Answer ALL Questions Birkbeck (University of London) Software and Programming 1 In-class Test 2.1 16 Mar 2017 Student Name Student Number Answer ALL Questions 1. What output is produced when the following Java program fragment

More information

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8 Epic Test Review 1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4 Write a line of code that outputs the phase Hello World to the console without creating a new line character. System.out.print(

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Debapriyo Majumdar Programming and Data Structure Lab M Tech CS I Semester I Indian Statistical Institute Kolkata August 7 and 14, 2014 Objects Real world objects, or even people!

More information

Arrays. Here is the generic syntax for an array declaration: type[] <var_name>; Here's an example: int[] numbers;

Arrays. Here is the generic syntax for an array declaration: type[] <var_name>; Here's an example: int[] numbers; Arrays What are they? An array is a data structure that holds a number of related variables. Thus, an array has a size which is the number of variables it can store. All of these variables must be of the

More information

Tutorial 6 CSC 201. Java Programming Concepts مبادئ الربجمة باستخدام اجلافا

Tutorial 6 CSC 201. Java Programming Concepts مبادئ الربجمة باستخدام اجلافا Tutorial 6 CSC 201 Java Programming Concepts مبادئ الربجمة باستخدام اجلافا Chapter 6: Classes and Objects 1. Classes & Objects What is an object? Real Objects Java Objects Classes Defining a class and

More information

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes. a and Interfaces Class Shape Hierarchy Consider the following class hierarchy Shape Circle Square Problem AND Requirements Suppose that in order to exploit polymorphism, we specify that 2-D objects must

More information

Program 20: //Design an Applet program to handle Mouse Events. import java.awt.*; import java.applet.*; import java.awt.event.*;

Program 20: //Design an Applet program to handle Mouse Events. import java.awt.*; import java.applet.*; import java.awt.event.*; Program 20: //Design an Applet program to handle Mouse Events. import java.awt.*; import java.applet.*; import java.awt.event.*; /* */ public

More information

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University Lecture 3 COMP1006/1406 (the Java course) Summer 2014 M. Jason Hinek Carleton University today s agenda assignments 1 (graded) & 2 3 (available now) & 4 (tomorrow) a quick look back primitive data types

More information

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. Inheritance Hierarchy. The Idea Behind Inheritance

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. Inheritance Hierarchy. The Idea Behind Inheritance Structural Programming and Data Structures Winter 2000 CMPUT 102: Dr. Osmar R. Zaïane Course Content Introduction Objects Methods Tracing Programs Object State Sharing resources Selection Repetition Vectors

More information

Array. Prepared By - Rifat Shahriyar

Array. Prepared By - Rifat Shahriyar Java More Details Array 2 Arrays A group of variables containing values that all have the same type Arrays are fixed length entities In Java, arrays are objects, so they are considered reference types

More information

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007 Name: Please fill in your Student Number and Name. Student Number : Student Number: University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ 2007 Supplementary Examination Question

More information

What is Inheritance?

What is Inheritance? Inheritance 1 Agenda What is and Why Inheritance? How to derive a sub-class? Object class Constructor calling chain super keyword Overriding methods (most important) Hiding methods Hiding fields Type casting

More information

Linked Lists. private int num; // payload for the node private Node next; // pointer to the next node in the list }

Linked Lists. private int num; // payload for the node private Node next; // pointer to the next node in the list } Linked Lists Since a variable referencing an object just holds the address of the object in memory, we can link multiple objects together to form dynamic lists or other structures. In our case we will

More information