Practice Problems: Inheritance & Polymorphism
|
|
- Caroline Fowler
- 6 years ago
- Views:
Transcription
1 Practice Problems: Inheritance & Polymorphism public class Foo public void method() System.out.println("foo "); public void method2() System.out.println("foo 2"); public String tostring() return "foo"; public class Bar extends Foo public void method2() System.out.println("bar 2"); public class Baz extends Foo public void method() System.out.println("baz "); public String tostring() return "baz"; public class Mumble extends Baz public void method2() System.out.println("mumble 2"); public class Polymorphism public static void main(string [] args) Foo[] pity = new Baz(), new Bar(), new Mumble(), new Foo() ; for (int i = 0; i < pity.length; i++) System.out.println(pity[i]); pity[i].method(); pity[i].method2(); System.out.println(); baz baz foo 2 foo foo bar 2 baz baz mumble 2 foo foo foo 2 *( ) method is inherited. Otherwise, method is overridden.. Tracing programs: The above is the program demonstrated in class. Now, what gets printed to the screen when we execute the following classes on the left?
2 public class A public int x = ; public void setx(int a) x=a; public class B extends A public int getb() setx(2); return x; public class C //trace program public static void main(string [] args) B b = new B(); System.out.println(a.x); System.out.println(b.getB()); public class A private int x = ; protected void setx(int a) x=a; protected int getx() return x; public class B extends A public int getb() setx(2); return getx(); public class C //trace program 2 public static void main(string [] args) B b = new B(); System.out.println(a.getX()); System.out.println(b.getB()); public class A protected int x = ; protected void setx(int a)x=a; protected int getx()return x; public class B extends A public int getb() setx(2); return x; public class C //trace program 3 public static void main(string [] args) B b = new B(); System.out.println(a.getX()); System.out.println(b.x); System.out.println(b.getB()); 2 direct access of attribute 2 use of method, instead of direct access of attribute, because the attribute is private! 2 protected
3 public class A protected int x = ; protected void setx(int a) x=a; protected int getx() return x; public class B extends A protected int x = 3; public int getx() return x; public int getb() return x; public class C //trace program 4 public static void main(string [] args) B b = new B(); System.out.println(a.getX()); System.out.println(b.getB()); System.out.println(b.getX()); System.out.println(a.x); System.out.println(b.x); public class A protected int x = ; protected void setx(int a) x=a; protected int getx() return x; public class B extends A protected int x = 3; public int getx() return x; public int getb() return x; public class C //trace program 5 public static void main(string [] args) A b = new B(); System.out.println(a.getX()); System.out.println(b.getX()); System.out.println(a.x); System.out.println(b.x); attribute shadowing, the above result is for comparison
4 public class A protected int x = ; protected void setx(int a) x=a; protected int getx() return x; public class B extends A protected int x = 3; public int getx() setx(2); return x; public int getb() return x; public class C //trace program 6 public static void main(string [] args) A b = new B(); System.out.println(a.getX()); System.out.println(b.getX()); System.out.println(a.x); System.out.println(b.x); public class Ham public void a() System.out.println("Ham a"); public void b() System.out.println("Ham b"); public String tostring() return "Ham"; public class Lamb extends Ham public void b() System.out.println("Lamb b"); public class Yam extends Lamb public void a() System.out.println("Yam a"); public String tostring() return "Yam"; 3 or in newer version of Java: 3 2 After setx(2), attribute of inherited part x = 2. Yam Spam a Lamb b Yam Yam a Lamb b Ham Ham a Ham b Ham Ham a Lamb b Check the order in the array declaration! public class Spam extends Yam public void a() System.out.println("Spam a"); public class Polymorphism2 //trace program 7
5 public static void main (String [] args) Ham[] food = new Spam(), new Yam(), new Ham(), new Lamb() ; for (int i = 0; i < food.length; i++) System.out.println(food[i]); food[i].a(); food[i].b(); System.out.println(); public class Ham int a = 0; int b = ; public void a() System.out.println("Ham + a); public void b() System.out.println("Ham + b); public String tostring() return "Ham + a + + b; public class Spam extends Ham int a = 2; public void a() System.out.println("Spam +a); public class Yam extends Spam int b = 3; public void a() System.out.println("Yam + a); public void b() System.out.println( Yam + b); public class Polymorphism3 //trace program 8 public static void main (String [] args) Ham[] food = new Spam(), new Yam(), new Ham(); for (int i = 0; i < food.length; i++) System.out.println(food[i]); food[i].a(); food[i].b(); Ham 0 Spam 2 Ham 0 Ham 0 Yam 2 Yam 3 0 Ham 0 Ham 0 Ham 0 Same tostring! Local method use local attribute. There is no polymorphism here. No type declaration twined. For instance, Spam 2. But for any attribute defined in multiple level inheritance, the closest one is inherited. For instance Yam 2. Attribute direct access via super class? Use the one in super class for instance, 0 and printed out at the end. System.out.println(food[i].a); System.out.println(food[i].b); System.out.println();
6 public class A private String x = "Ax"; protected String y = "Ay"; public String z = "Az"; public String tostring() return x + y + z; public static void main( String [] args) System.out.println(a); public class B extends A private String x = "Bx"; public String z = "Bz"; public String tostring() return x + y + z; public static void main( String [] args) B b = new B(); System.out.println(b); public class C extends A private String x = "Cx"; public static void main( String [] args) C c = new C(); System.out.println(c.x); System.out.println(c); public class D extends C //trace program 9 private String x = "Dx"; public String z = "Dz"; public static void main( String [] args) D d = new D(); System.out.println(d.x); System.out.println(d.y); System.out.println(d.z); System.out.println(d); C c = new D(); // Error: System.out.println(c.x); System.out.println(c.y); System.out.println(c.z); System.out.println(c); When A is executed, it displays: AxAyAz The println statement implicitly calls a.tostring(), which creates a string containing the concatenation of the variables x, y, and z. Once this concatenated String ("AxAyAz") is returned, it gets printed to the screen. When B is executed, it displays: BxAyBz The println statement implicitly calls b.tostring(), which refers to the overriding tostring() method defined in subclass B. This tostring method says to concatenate x+y+z (like the one defined in class A), but now it is referring to variables x, y, and z in the B class. Two of those variables are defined locally x and z. These variables hide (or "shadow") the x and z variables defined in class A. The third variable, y, is inherited from A. As a result, the concatenation in the tostring method produces a String that looks like "BxAyBz", which then gets printed.
7 When C is executed, it displays: Cx AxAyAz When the first println statement executes, it refers directly to c.x, which is defined locally. So that prints out "Cx". When the second println statement executes, it refers to C's inherited tostring method. The inherited tostring method is defined in class A, which returns the concatenation of x, y, and z from class A. So that returns "AxAyAz", which gets printed. When D is executed, it displays: Dx Ay Dz DxAyDz Ay Az DxAyDz The first 3 lines print the values of x, y, and z inside of d. Since x and z are defined inside of class D, those values get printed out. y is inherited from class A, so "Ay" gets printed out. The next line prints the return value of D's tostring method. The tostring method is defined locally to override the inherited one (unlike in the example for class C, where the tostring method is inherited instead of overridden). Because the tostring method is overridden, when it refers to x, y, and z, it refers to the variables inside of class D. So this returns "DxAyDz". Compare this to the inherited tostring method in class C, which returns "AxAyAz". The next two lines use a variable with static type C to refer to an object of dynamic type D. Notice that it is an error to try to print (or refer to) c.x. That's because 'x' is private in class C, and this code is written inside class D. Also notice that c.z is "Az", whereas d.z is "D.z". For fields, Java uses the value of the static type's field (in this case, the value of z from class C, which is inherited from class A and has value "Az"). The last line prints the value of c.tostring(). Java uses the value of a the static type's field, but the dynamic type's methods. Variable c has dynamic type D, because it refers to an object of type D. So Java uses the tostring method defined in class D, which returns the values of x, y, and z within class D (or "DxAyDz"). Notice the difference between how fields get handled, and how methods get handled. The field c.z refers to the field defined in class C (which is inherited from class A). The method c.tostring() refers to the method defined in class D, not class C. I have still not figured out any reason why Java does shadow things this way for fields. It's very confusing, and it can lead to very hard-to-fix bugs. In general, it is HIGHLY RECOMMENDED that you AVOID defining fields with the same name as a superclass's field. Sometimes though (like when you're extending a superclass from the Java API), you may not know what the superclass's fields are called, and in that case, you just have to guess.
8 2. Program Development a. Below is a partially filled-out Time class, which stores the hour and minute in private attributes. The constructor is also given. public class Time implements Comparable private int hour =0; private int minute =0; public Time (int h, int m) if (h<0 h>23) return; if(m<0 m>59) return; hour = h; minute = m; // additional (instance) methods will go here. Please complete the above Time class with methods compareto and tostring, in order to support the following application class and reach the desired result: import java.util.arrays; public class TimeCheck public static void main(string args[]) Time [] t = new Time(3, 5), new Time(6, 0), new Time(4, 29), new Time(, 59), new Time(23, ), new Time(2, 59), new Time (4, 9) ; Arrays.sort(t); for (Time f: t) System.out.println(f+",");
9 public class Time implements Comparable 2 private int hour =0; 3 private int minute =0; 4 public Time (int h, int m) 5 if (h<0 h>23) return; 6 if(m<0 m>59) return; 7 hour = h; 8 minute = m; // 0 pts 3 public int gethour() 4 return hour; 5 6 public int getminute() 7 return minute; // = =8 pts 2 public int compareto(object o) 22 if( o!=null && (o instanceof Time)) 23 Time r = (Time) o; 24 int t = hour * 60 + minute; 25 int t2 = r.hour * 60 + r.minute; 26 if (t<t2) return -; 27 else if(t>t2) return ; 28 else return 0; return -; 3 32 // 6 pts 33 public String tostring() 34 return "("+hour+", "+minute+")"; b. Given the super class Student (contained in the package that is available at Please complete the following class Records, in order to support the weighted score grading by the Test program and reach the desire result by using the input file trial. import javax.swing.joptionpane; import java.io.*; import java.util.*; public class Test public static void main(string [] args) Records [] t = new Records("CSC240", 2, 4, 3, 60, 0, 30), // 2 tests, 4 quizzes, and 3 assignments new Records("CSC32",, 3, 3, 25, 5, 60),
10 // test, 3 quizzes, and 3 assignments new Records("CSC5", 3, 0, 3, 60, 0, 40); // 3 tests, 0 quiz, and 3 assignments String filename = JOptionPane.showInputDialog("Enter the file name: "); File inputfile = new File (filename); try Scanner input = new Scanner(inputFile); String val; while(input.hasnext()) val = input.nextline(); String [] data = val.split(" "); int index = Integer.parseInt(data[0]); char opt = data[].tolowercase().charat(0); int [] s = new int[data.length-2]; for(int i = 0; i<s.length; i++) s[i] = Integer.parseInt(data[i+2]); switch(opt) case 't': t[index].set_test(s); break; case 'q': t[index].set_quiz(s); break; case 'a': t[index].set_assignment(s); break; input.close(); catch (FileNotFoundException e) System.out.println("file reading fails."); for(int i = 0; i<t.length; i++) Records tmp = t[i]; tmp.grading(); System.out.println(tmp);
11 In detail, the class Records should have the private attributes and the constructor as follows: import java.util.arrays; public class Records extends Student private int [] test = null; private int [] quiz = null; private int [] assignment = null; public Records (String name, int tn, int qn, int an, int tw, int qw, int aw) super(name, tw, qw, aw); test = new int [tn]; quiz = new int [qn]; assignment = new int [an]; This class should also have the following methods: ) set_test: that will accept a group of test scores in an integer array. The values will copy to the private attribute array test. 2) set_quiz: that will accept a group of quiz scores in an integer array. The values will copy to the private attribute array quiz. 3) set_assignment: that will accept a group of assignment scores in an integer array. The values will copy to the private attribute array assignment. 4) get_test: will calculate and return the average of test scores in attribute array test. 5) get_quiz: will calculate and return the average of quiz scores in attribute array quiz. 6) get_assignment: will calculate and return the average of assignment scores in attribute array assignment. 7) grading: will call the method letter_grading of the super class to set the GPA score (i.e., attribute of super class). 8) tostring: will return the information in a String, which carries both the course information and the scores of tests, quizzes, and assignments. GPA information is also needed.
12 import javax.swing.joptionpane; 2 import java.util.arrays; 3 import java.io.*; 4 import java.util.*; 5 6 public class Records extends Student 7 private int [] test = null; 8 private int [] quiz = null; 9 private int [] assignment = null; 0 public Records(String name, int tn, int qn, int an, int tw, int qw, int aw) 2 super(name, tw, qw, aw); 3 test = new int [tn]; 4 quiz = new int [qn]; 5 assignment = new int [an]; // = = 0 pts 9 public void set_test(int [] s) 20 if (s.length!=test.length) return; // the size is determined for(int i = 0; i<test.length; i++) 23 test[i] = s[i]; // = 0 pts; 28 public void set_quiz(int [] s) 29 if (s.length!=quiz.length) return; 30 3 for(int i = 0; i<quiz.length; i++) 32 quiz[i] = s[i]; // = 0 pts 37 public void set_assignment(int [] s) 38 if (s.length!=assignment.length) return; for(int i = 0; i<assignment.length; i++) 4 assignment[i] = s[i]; // 0 pts 46 public double get_test() 47 double total = 0.0; 48 if(test.length<=0) return 0; 49 for(int i = 0; i<test.length; i++) 50 total+= test[i]; 5 return total/test.length; // 0 pts 55 public double get_quiz() 56 double total = 0.0; 57 if(quiz.length<=0) return 0;
13 58 for(int i = 0; i<quiz.length; i++) 59 total+= quiz[i]; 60 return total/quiz.length; // 0 pts 64 public double get_assignment() 65 double total = 0.0; 66 if(assignment.length<=0) return 0; 67 for(int i = 0; i<assignment.length; i++) 68 total+= assignment[i]; 69 return total/assignment.length; // 0 pts 73 public void grading() 74 double [] tga = get_test(), get_quiz(), get_assignment(); 75 letter_grading(tga); // 5 pts 79 public String tostring() 80 String ret = ""; 8 if(test.length>0) 82 ret+="test score:"+arrays.tostring(test)+"\n"; 83 if(quiz.length>0) 84 ret+="quiz score:"+arrays.tostring(quiz)+"\n"; 85 if(assignment.length>0) 86 ret+="assignment score:"+arrays.tostring(assignment)+"\n"; 87 grading(); 88 ret+="gpa: "+get_gpa()+"\n"; 89 return ret;
Practice Problems: Inheritance & Polymorphism
Practice Problems: Inheritance & Polymorphism public class Foo public void method1() System.out.println("foo 1"); public void method2() System.out.println("foo 2"); public String tostring() return "foo";
More informationPractice Problems: Inheritance & Polymorphism
Practice Problems: Inheritance & Polymorphism public class Foo public void method() System.out.println("foo "); public void method2() System.out.println("foo 2"); public String tostring() return "foo";
More informationTopic 32 - Polymorphism
Topic 32 - Polymorphism Polymorphism polymorphism: Ability for the same code to be used with different types of objects and behave differently with each. System.out.println can print any type of object.
More informationCS 112 Introduction to Programming. (Spring 2012)
CS 112 Introduction to Programming (Spring 2012) Lecture #38: Final Review; Critter Tournament Zhong Shao Department of Computer Science Yale University Office: 314 Watson http://flint.cs.yale.edu/cs112
More informationCS 112 Introduction to Programming. Final Review. Topic: Static/Instance Methods/Variables: I am confused
Overview Course Overview (From Lecture 1) CS 112 Introduction to Programming What is CS112? What is COS 126? Broad, but technical, intro to computer science. A broad, programming-centric introduction to
More informationBBM 102 Introduction to Programming II
BBM 102 Introduction to Programming II Spring 2018 Polymorphism 1 Today Inheritance revisited Comparing objects : equals() method instanceof keyword Polymorphism 2 Visibility Revisited All variables and
More informationCSC 240 Computer Science III Spring 2018 Midterm Exam. Name
CSC 240 Computer Science III Spring 2018 Midterm Exam Name Page Points Score 2 9 4-6 53 7-10 38 Total 100 1 P age 1. Tracing programs (1 point each value): For each snippet of Java code on the left, write
More informationimport javax.swing.joptionpane; import java.util.*; import java.io.*;
import javax.swing.joptionpane; import java.util.*; import java.io.*; public class PolyA extends SingleLinkedList { Q1: why extends A1: Because we do not want to copy the program of SingleLinkedList
More informationInheritance. Writing classes. Writing more classes. Why are they very similar? Employee class. Secretary class. Readings: 9.1
Writing classes Inheritance Readings: 9.1 Write an Employee class with methods that return values for the following properties of employees at a particular company: Work week: 40 hours Annual salary: $40,000
More informationBBM 102 Introduction to Programming II Spring 2017
BBM 102 Introduction to Programming II Spring 2017 Polymorphism Instructors: Ayça Tarhan, Fuat Akal, Gönenç Ercan, Vahid Garousi TAs: Selma Dilek, Selim Yılmaz, Selman Bozkır 1 Today Inheritance revisited
More informationWhat is Polymorphism? CS 112 Introduction to Programming
What is Polymorphism? CS 112 Introduction to Programming (Spring 2012) q polymorphism: Ability for the same code to be used with different types of objects and behave differently with each. Lecture #33:
More informationHAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.
HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all
More informationCOMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code
COMPUTER SCIENCE DEPARTMENT PICNIC Welcome to the 2016-2017 Academic year! Meet your faculty, department staff, and fellow students in a social setting. Food and drink will be provided. When: Saturday,
More informationThe software crisis. code reuse: The practice of writing program code once and using it in many contexts.
Inheritance The software crisis software engineering: The practice of conceptualizing, designing, developing, documenting, and testing largescale computer programs. Large-scale projects face many issues:
More informationBig software. code reuse: The practice of writing program code once and using it in many contexts.
Inheritance Big software software engineering: The practice of conceptualizing, designing, developing, documenting, and testing largescale computer programs. Large-scale projects face many issues: getting
More informationThe software crisis. code reuse: The practice of writing program code once and using it in many contexts.
Inheritance The software crisis software engineering: The practice of conceptualizing, designing, developing, documenting, and testing largescale computer programs. Large-scale projects face many issues:
More information1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'
Practice questions: 1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4' 2. Will System.out.println((char)4) display 4? a. Yes b. No 3. The expression "Java
More informationFall CS 101: Test 2 Name UVA ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17.
Grading Page 1 / 4 Page3 / 20 Page 4 / 13 Page 5 / 10 Page 6 / 26 Page 7 / 17 Page 8 / 10 Total / 100 1. (4 points) What is your course section? CS 101 CS 101E Pledged Page 1 of 8 Pledged The following
More informationObjectives. Inheritance. Inheritance is an ability to derive a new class from an existing class. Creating Subclasses from Superclasses
Objectives Inheritance Students should: Understand the concept and role of inheritance. Be able to design appropriate class inheritance hierarchies. Be able to make use of inheritance to create new Java
More informationPractice Questions for Final Exam: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course
: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course 1. Given the following hierarchy: class Alpha {... class Beta extends Alpha {... class Gamma extends Beta {... In what order
More informationHAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.
HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all
More informationI pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class.
Name: Covers Chapters 1-3 50 mins CSCI 1301 Introduction to Programming Armstrong Atlantic State University Instructor: Dr. Y. Daniel Liang I pledge by honor that I will not discuss this exam with anyone
More informationExercise: Singleton 1
Exercise: Singleton 1 In some situations, you may create the only instance of the class. 1 class mysingleton { 2 3 // Will be ready as soon as the class is loaded. 4 private static mysingleton Instance
More informationCS 251 Intermediate Programming Inheritance
CS 251 Intermediate Programming Inheritance Brooke Chenoweth University of New Mexico Spring 2018 Inheritance We don t inherit the earth from our parents, We only borrow it from our children. What is inheritance?
More informationChapter 12: Inheritance
Chapter 12: Inheritance Objectives Students should Understand the concept and role of inheritance. Be able to design appropriate class inheritance hierarchies. Be able to make use of inheritance to create
More informationCOP 3330 Final Exam Review
COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time
More informationInstance Members and Static Members
Instance Members and Static Members You may notice that all the members are declared w/o static. These members belong to some specific object. They are called instance members. This implies that these
More informationArgument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.
Local Variable Initialization Unlike instance vars, local vars must be initialized before they can be used. Eg. void mymethod() { int foo = 42; int bar; bar = bar + 1; //compile error bar = 99; bar = bar
More informationJAVA 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 informationName Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?
1. Overriding Methods A subclass can modify behavior inherited from a parent class. A subclass can create a method with different functionality than the parent s method but with the same: Name Return type
More informationFinal Exam Practice Questions
Final Exam Practice Questions 1. Short Answer Questions (10 points total) (a) Given the following hierarchy: class Alpha {... class Beta extends Alpha {... class Gamma extends Beta {... What order are
More informationCSCI 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 informationObject-Oriented Concepts
JAC444 - Lecture 3 Object-Oriented Concepts Segment 2 Inheritance 1 Classes Segment 2 Inheritance In this segment you will be learning about: Inheritance Overriding Final Methods and Classes Implementing
More informationOverriding Variables: Shadowing
Overriding Variables: Shadowing We can override methods, can we override instance variables too? Answer: Yes, it is possible, but not recommended Overriding an instance variable is called shadowing, because
More informationLecture 2: Java & Javadoc
Lecture 2: Java & Javadoc CS 62 Fall 2018 Alexandra Papoutsaki & William Devanny 1 Instance Variables or member variables or fields Declared in a class, but outside of any method, constructor or block
More informationCS 201, Fall 2016 Sep 28th Exam 1
CS 201, Fall 2016 Sep 28th Exam 1 Name: Question 1. [5 points] Write code to prompt the user to enter her age, and then based on the age entered, print one of the following messages. If the age is greater
More informationCmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects
CmSc 150 Fundamentals of Computing I Lesson 28: Introduction to Classes and Objects in Java 1. Classes and Objects True object-oriented programming is based on defining classes that represent objects with
More informationCLASS DESIGN. Objectives MODULE 4
MODULE 4 CLASS DESIGN Objectives > After completing this lesson, you should be able to do the following: Use access levels: private, protected, default, and public. Override methods Overload constructors
More informationCS260 Intro to Java & Android 03.Java Language Basics
03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance
More informationFull file at Chapter 2 - Inheritance and Exception Handling
Chapter 2 - Inheritance and Exception Handling TRUE/FALSE 1. The superclass inherits all its properties from the subclass. ANS: F PTS: 1 REF: 76 2. Private members of a superclass can be accessed by a
More informationJava 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 informationInheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.
Inheritance Inheritance is the act of deriving a new class from an existing one. Inheritance allows us to extend the functionality of the object. The new class automatically contains some or all methods
More informationCSCI 355 LAB #2 Spring 2004
CSCI 355 LAB #2 Spring 2004 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 informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Interface Abstract data types Version of January 26, 2013 Abstract These lecture notes are meant
More informationCSC 1214: Object-Oriented Programming
CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:
More informationCS 2334: Programming Structures and Abstractions: Exam 1 October 3, 2016
General instructions: CS 2334: Programming Structures and Abstractions: Exam 1 October 3, 2016 Please wait to open this exam booklet until you are told to do so. This examination booklet has 13 pages.
More informationJava Object Oriented Design. CSC207 Fall 2014
Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code
More informationMore 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 informationBuilding Java Programs. Inheritance and Polymorphism
Building Java Programs Inheritance and Polymorphism Input and output streams stream: an abstraction of a source or target of data 8-bit bytes flow to (output) and from (input) streams can represent many
More informationPractice 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 informationJava and OOP. Part 5 More
Java and OOP Part 5 More 1 More OOP More OOP concepts beyond the introduction: constants this clone and equals inheritance exceptions reflection interfaces 2 Constants final is used for classes which cannot
More informationCSE 143 Lecture 25. I/O Streams; Exceptions; Inheritance. read 9.3, 6.4. slides adapted from Marty Stepp
CSE 143 Lecture 25 I/O Streams; Exceptions; Inheritance read 9.3, 6.4 slides adapted from Marty Stepp http://www.cs.washington.edu/143/ Input and output streams stream: an abstraction of a source or target
More informationcoe318 Lab 2 ComplexNumber objects
Objectives Overview coe318 Lab 2 objects Implement a class. Learn how immutable objects work. Week of September 15, 2014 Create a project with more than one class. Duration: one week. In mathematics, complex
More informationProgramming overview
Programming overview Basic Java A Java program consists of: One or more classes A class contains one or more methods A method contains program statements Each class in a separate file MyClass defined in
More informationA base class (superclass or parent class) defines some generic behavior. A derived class (subclass or child class) can extend the base class.
Inheritance A base class (superclass or parent class) defines some generic behavior. A derived class (subclass or child class) can extend the base class. A subclass inherits all of the functionality of
More informationCS 231 Data Structures and Algorithms, Fall 2016
CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard
More informationOverview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008
Overview Lecture 7: Inheritance and GUIs Written by: Daniel Dalevi Inheritance Subclasses and superclasses Java keywords Interfaces and inheritance The JComponent class Casting The cosmic superclass Object
More informationCSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community
CSCI-12 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community http://csc.cs.rit.edu 1. Provide a detailed explanation of what the following code does: 1 public boolean checkstring
More informationCSCI 136 Written Exam #0 Fundamentals of Computer Science II Spring 2013
CSCI 136 Written Exam #0 Fundamentals of Computer Science II Spring 2013 Name: This exam consists of 5 problems on the following 7 pages. You may use your single-side hand-written 8 ½ x 11 note sheet during
More informationRules and syntax for inheritance. The boring stuff
Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for
More informationCSE 143 Lecture 22. I/O Streams; Exceptions; Inheritance. read 9.3, 6.4. slides created by Marty Stepp
CSE 143 Lecture 22 I/O Streams; Exceptions; Inheritance read 9.3, 6.4 slides created by Marty Stepp http://www.cs.washington.edu/143/ Input and output streams stream: an abstraction of a source or target
More informationCSE 143 Lecture 21. I/O Streams; Exceptions; Inheritance. read 9.3, 6.4. slides created by Marty Stepp
CSE 143 Lecture 21 I/O Streams; Exceptions; Inheritance read 9.3, 6.4 slides created by Marty Stepp http://www.cs.washington.edu/143/ Input and output streams stream: an abstraction of a source or target
More informationSoftware 1 with Java. Initialization. Initialization. Initialization. Pass by Value. Initialization. Recitation No. 11 (Summary)
Software 1 with Java Recitation No. 11 (Summary) public class Foo { static int bar; public static void main (String args []) { bar += 1; System.out.println("bar = " + bar); The Does output the code is:
More informationJAVA 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 informationJAVA OPERATORS GENERAL
JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators
More informationAP CS Unit 6: Inheritance Notes
AP CS Unit 6: Inheritance Notes Inheritance is an important feature of object-oriented languages. It allows the designer to create a new class based on another class. The new class inherits everything
More informationWhat 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 informationCIS 110: Introduction to computer programming
CIS 110: Introduction to computer programming Lecture 25 Inheritance and polymorphism ( 9) 12/3/2011 CIS 110 (11fa) - University of Pennsylvania 1 Outline Inheritance Polymorphism Interfaces 12/3/2011
More informationInheritance (continued) Inheritance
Objectives Chapter 11 Inheritance and Polymorphism Learn about inheritance Learn about subclasses and superclasses Explore how to override the methods of a superclass Examine how constructors of superclasses
More informationCSC207H: Software Design. Java + OOP. CSC207 Winter 2018
Java + OOP CSC207 Winter 2018 1 Why OOP? Modularity: code can be written and maintained separately, and easily passed around the system Information-hiding: internal representation hidden from the outside
More informationF 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(A) 99 (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution
Ch 5 Arrays Multiple Choice 01. An array is a (A) (B) (C) (D) data structure with one, or more, elements of the same type. data structure with LIFO access. data structure, which allows transfer between
More informationAbstract 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 informationJava Magistère BFA
Java 101 - Magistère BFA Lesson 3: Object Oriented Programming in Java Stéphane Airiau Université Paris-Dauphine Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 1 Goal : Thou Shalt
More informationObject Oriented Programming. Java-Lecture 11 Polymorphism
Object Oriented Programming Java-Lecture 11 Polymorphism Abstract Classes and Methods There will be a situation where you want to develop a design of a class which is common to many classes. Abstract class
More informationCS1083 Week 2: Arrays, ArrayList
CS1083 Week 2: Arrays, ArrayList mostly review David Bremner 2018-01-08 Arrays (1D) Declaring and using 2D Arrays 2D Array Example ArrayList and Generics Multiple references to an array d o u b l e prices
More informationQuestions Answer Key Questions Answer Key Questions Answer Key
Benha University Term: 2 nd (2013/2014) Class: 2 nd Year Students Subject: Object Oriented Programming Faculty of Computers & Informatics Date: 26/4/2014 Time: 1 hours Exam: Mid-Term (A) Name:. Status:
More informationCMSC 132: Object-Oriented Programming II
CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation
More informationCS Programming I: Inheritance
CS 200 - Programming I: Inheritance Marc Renault Department of Computer Sciences University of Wisconsin Madison Fall 2017 TopHat Sec 3 (PM) Join Code: 719946 TopHat Sec 4 (AM) Join Code: 891624 Inheritance
More informationProgramming II (CS300)
1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions and
More informationAP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS
AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this
More informationLanguage Features. 1. The primitive types int, double, and boolean are part of the AP
Language Features 1. The primitive types int, double, and boolean are part of the AP short, long, byte, char, and float are not in the subset. In particular, students need not be aware that strings are
More informationThe 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 informationCSE 142, Spring 2009, Sample Final Exam #2. Good luck!
CSE 142, Spring 2009, Sample Final Exam #2 Name: Section: Student ID #: TA: Rules: You have 110 minutes to complete this exam. You will receive a deduction if you keep working after the instructor calls
More informationImplements vs. Extends When Defining a Class
Implements vs. Extends When Defining a Class implements: Keyword followed by the name of an INTERFACE Interfaces only have method PROTOTYPES You CANNOT create on object of an interface type extends: Keyword
More informationCMPS 11 Intermediate Programming Midterm 2 Review Problems
CMPS 11 Intermediate Programming Midterm 2 Review Problems 1. Determine the output of the following Java program. Notice that the method fcn2() is overloaded, so there are really three distinct functions
More informationCS 101 Exam 2 Spring Id Name
CS 101 Exam 2 Spring 2005 Email Id Name This exam is open text book and closed notes. Different questions have different points associated with them. Because your goal is to maximize your number of points,
More informationINSTRUCTIONS TO CANDIDATES
NATIONAL UNIVERSITY OF SINGAPORE SCHOOL OF COMPUTING MIDTERM ASSESSMENT FOR Semester 2 AY2017/2018 CS2030 Programming Methodology II March 2018 Time Allowed 90 Minutes INSTRUCTIONS TO CANDIDATES 1. This
More informationCS 113 PRACTICE FINAL
CS 113 PRACTICE FINAL There are 13 questions on this test. The value of each question is: 1-10 multiple choice (4 pt) 11-13 coding problems (20 pt) You may get partial credit for questions 11-13. If you
More informationCMPS 12A Introduction to Programming Midterm 2 Review Problems
CMPS 12A Introduction to Programming Midterm 2 Review Problems Note: Do problems 4, 5 and 9 from the Midterm 1 review sheet. Problems 6, 8 and 9 from this sheet have not yet been covered. We'll see how
More informationJava provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:
Basic Operators Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators
More informationJava classes cannot extend multiple superclasses (unlike Python) but classes can implement multiple interfaces.
CSM 61B Abstract Classes & Interfaces Spring 2017 Week 5: February 13, 2017 1 An Appealing Appetizer 1.1 public interface Consumable { public void consume (); public abstract class Food implements Consumable
More informationChapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber
Chapter 10 Inheritance and Polymorphism Dr. Hikmat Jaber 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the
More informationProgramming II (CS300)
1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions
More informationNATIONAL UNIVERSITY OF SINGAPORE
NATIONAL UNIVERSITY OF SINGAPORE SCHOOL OF COMPUTING TERM TEST #1 Semester 1 AY2006/2007 CS1101X/Y/Z PROGRAMMING METHODOLOGY 16 September 2006 Time Allowed: 60 Minutes INSTRUCTIONS 1. This question paper
More informationComputer Science II (20073) Week 1: Review and Inheritance
Computer Science II 4003-232-01 (20073) Week 1: Review and Inheritance Richard Zanibbi Rochester Institute of Technology Review of CS-I Hardware and Software Hardware Physical devices in a computer system
More informationRecords. ADTs. Objects as Records. Objects as ADTs. Objects CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 15: Objects 25 Feb 05
Records CS412/CS413 Introduction to Compilers Tim Teitelbaum Lecture 15: Objects 25 Feb 05 Objects combine features of records and abstract data types Records = aggregate data structures Combine several
More information1 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 informationCS159. Nathan Sprague
CS159 Nathan Sprague What s wrong with the following code? 1 /* ************************************************** 2 * Return the mean, or -1 if the array has length 0. 3 ***************************************************
More information