Java Review I. What is a stream? What is a byte stream? what is a character stream? What types of files does a program will typically handle?

Slides:



Advertisements
Similar presentations
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
Advertisements

Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
Unit 201 FILE IO Types of files Opening a text file for reading Reading from a text file Opening a text file for writing/appending Writing/appending to.
1 Chapter 7 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
1 Chapter 7 Inheritance, Polymorphism, and Scope.
Chapter 10 Inheritance, Polymorphism, and Scope. 2 Knowledge Goals Understand the hierarchical nature of classes in object-oriented programming Understand.
1 Text File I/O Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
Chapter 11: Inheritance and Polymorphism Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
C++ fundamentals.
Some Quick Reviews of Java. Background Java was developed in the early 90s by Sun Microsystems Java is a high-level language Java programs are portable.
Java File I/O (Continued). File I/O in Java Like every other programming language, Java supports the writing to and reading from different files with.
CMSC 202 Interfaces. 11/20102 Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Comp 249 Programming Methodology Chapter 8 - Polymorphism Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,
Final Reviews The final exam is on May 14th from 11:00 am - 2:00 pm at the room CBB 104. It covers everything about Java!
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Input / Output Chapter 13.  We use files all the time  Programs are files  Documents are files  We want them to be “permanent”  To last beyond execution.
Programming With Java ICS201 University Of Ha’il1 Chapter 8 Polymorphism and Abstract Classes.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
The Java Programming Language
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Java Interfaces. Interfaces An interface is something like an extreme case of an abstract class – However, an interface is not a class – It is a type.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Programming in Java CSCI-2220 Object Oriented Programming.
CMSC 202 Text File I/O. Aug 8, Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
Chapter 10 Text Files Section 10.2 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Object Oriented Programming
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Java Polymorphism. What we have learned Polymorphism is one of the three very powerful and useful mechanisms offered by OOP. What are the other two?
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 15 Inheritance.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
Classes, Interfaces and Packages
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
1 Text File Input and Output. Objectives You will be able to Write text files from your Java programs. Read text files in your Java programs. 2.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Modern Programming Tools And Techniques-I
Object-Oriented Concepts
OO Design and Programming II I/O: Reading and Writing
CMSC 202 Text File I/O.
I/O Basics.
Comp 249 Programming Methodology
ATS Application Programming: Java Programming
CSS161: Fundamentals of Computing
Computer Science II Exam 1 Review.
CSS 161: Fundamentals of Computing
Chapter 9 Carrano Chapter 10 Small Java
Streams A stream is an object that enables the flow of data between a program and some I/O device or file If the data flows into a program, then the stream.
Presentation transcript:

Java Review I

What is a stream? What is a byte stream? what is a character stream? What types of files does a program will typically handle?

What is a stream? What is a byte stream? what is a character stream? What types of files does a program will typically handle? A stream is an object that allows for the flow of data between your program and some I/O device or some file Byte stream inputs and outputs 8-bit bytes ASCII text files and binary files

How to write to a text file?

Use PrintWriter class Import. import java.io.PrintWriter; import java.io.FileOutputStream; import java.io.FileNotFoundException;

How to write to a text file? Use PrintWriter class Import. import java.io.PrintWriter; import java.io.FileOutputStream; import java.io.FileNotFoundException; PrintWriter outputStreamName; outputStreamName = new PrintWriter( new FileOutputStream (FileName)); PrintWriter outputStreamName; outputStreamName = new PrintWriter(FileName); Create a PrintWriter object

How to write to a text file? Use PrintWriter class Import. import java.io.PrintWriter; import java.io.FileOutputStream; import java.io.FileNotFoundException; PrintWriter outputStreamName; outputStreamName = new PrintWriter( new FileOutputStream (FileName)); PrintWriter outputStreamName; outputStreamName = new PrintWriter(FileName); Create a PrintWriter object If the file is open successfully, the methods, print(…) and println(…), can be used to output text information into the file.

How to write to a text file? Use PrintWriter class Import. import java.io.PrintWriter; import java.io.FileOutputStream; import java.io.FileNotFoundException; PrintWriter outputStreamName; outputStreamName = new PrintWriter( new FileOutputStream (FileName)); PrintWriter outputStreamName; outputStreamName = new PrintWriter(FileName); Create a PrintWriter object If the file is open successfully, the methods, print(…) and println(…), can be used to output text information into the file. Remember to put this in an Exception handling block

How to close a file? writer_or_reader_obj.close();

Example import java.io.PrintWriter; import java.io.FileOutputStream; import java.io.FileNotFoundException; public class WriteTextFileDemo { public static void main (String[] args) { PrintWriter outputStreamName; String Filename = "test.txt"; try { outputStreamName = new PrintWriter(new FileOutputStream (Filename)); outputStreamName.println("test text file!"); outputStreamName.println("succeeded!"); // Do other fancy output … outputStreamName.close(); } catch(FileNotFoundException e) { System.out.println("File "+Filename+"cannot be found."); System.exit(0); }

How to append to an existing text file?

Flushing to a text file In some situations, you do not want to overwrite what has been recorded in the existing file. The new output will be appended to the previous output. To address that, we need to use the FileWriter and BufferedWriter classes PrintWriter outputStreamName = new PrintWriter( new FileOutputStream(FileName, true)); Use the following format to open the file to force flushing the buffer to the file! PrintWriter outputStreamName = new PrintWriter( new BufferedWriter( new FileWriter(FileName, true))); Note that the slides from the textbook were the 4 th edition, which are not correct about the appending to the text file!!

How to read from a text file using a Scanner object?

Using Scannar class Scanner StreamObject = new Scanner(new FileInputStream(FileName)); Import. import java.util.Scannar; import java.io.FileInputStream; import java.io.FileNotFoundException; Create a Scanner object

How to read from a text file using a Scanner object? Using Scannar class Scanner StreamObject = new Scanner(new FileInputStream(FileName)); Import. import java.util.Scanner; import java.io.FileInputStream; import java.io.FileNotFoundException; Create a Scanner object If successful, use the following to read from file nextInt() nextShort() nextLong() nextByte() nextDouble() nextLine() ……

How to determine the end of the file using a Scanner object?

hasNextInt() hasNextShort() hasNextLong() hasNextByte() hasNextDouble() hasNextLine() ……

Remember to put file I/O in an Exception handling block. Do not forget to close the file!

Example Read one integer from the file at a time. Integers are separated by empty space. Read one line of string.

Testing the end of the text file Example: adding line number to the file Given input file: The output file will be

How to read from a text file using a BufferedReader object?

import java.io.BufferedReader; import java.io.FileReader; import java.io.FileNotFoundException; import java.io.IOException; BufferedReader readerObject; readerObject = new BufferedReader(new FileReader(FileName));

How to read from a text file using a BufferedReader object? import java.io.BufferedReader; import java.io.FileReader; import java.io.FileNotFoundException; import java.io.IOException; BufferedReader readerObject; readerObject = new BufferedReader(new FileReader(FileName)); After the file is successfully opened, the readLine() and read() methods can be used to read from the file. The readLine method is the same method used to read from the keyboard, but in this case it would read from a file. The read method reads a single character, and returns a value (of type int ) that corresponds to the character read.

How to determine the end of a text file using a BufferedReader object?

When using the readLine() method, it will return null if reaching or trying to read beyond the end of the file. When using the read() method, it will return -1 if reaching or trying to read beyond the end of the file.

Remember to put file I/O in an Exception handling block. Do not forget to close the file!

Using BufferReader class to read from a text file Given input file Output will be

EARLIER CONTENT

Class in Java Classes are the most important language feature that make object- oriented programming (OOP) possible. – Combination of both attributes and behaviors – Can be used to generate many objects with the same behaviors – Information hidden and encapsulation Programming in Java consists of defining a number of classes – Every program is a class – All helping software consists of classes – All programmer-defined types are classes Classes are central to Java All classes inherit from the Object class

How to define a class in Java? How did we do that in C++? class class_name { public: //member func. … private: // attribute list }; How should we do that in Java? public class class_name { public member func1 public member func2 … protected member var1 private member var2 … } No semi-column!

How to define a class in Java? How did we do that in C++? class class_name { public: //member func. … private: // attribute list }; How should we do that in Java? public class class_name { public member func1 public member func2 … protected member var1 private member var2 … } No semi-column! How do different access modifiers affect the access of members?

One Example package One; public class DayOfYear { public DayOfYear() {month = day = 1;} public DayOfYear(int monthVal, int dayVal) {month = monthVal; day = dayVal; } void input(int m, int d) {month = m; day = d;} public void output() { System.out.println(“month=“ +month+ ”, day=“ +day); } private int month, day; } package Two; public class TestDemo { public static void main() { DayOfYear date1(3,18), examdate(); System.out.print(“date1.month=“ +date1.month+ ”, date1.day=“ +date1.day); examdate.input(3,20); examdate.output(); } What will be the output of this code?

One Example package One; public class DayOfYear { public DayOfYear() {month = day = 1;} public DayOfYear(int monthVal, int dayVal) {month = monthVal; day = dayVal; } void input(int m, int d) {month = m; day = d;} public void output() { System.out.println(“month=“ +month+ ”, day=“ +day); } private int month, day; } package Two; public class TestDemo { public static void main() { DayOfYear date1(3,18), examdate(); System.out.print(“date1.month=“ +date1.month+ ”, date1.day=“ +date1.day); examdate.input(3,20); examdate.output(); } Compiling error! Why?

One Example package One; public class DayOfYear { public DayOfYear() {month = day = 1;} public DayOfYear(int monthVal, int dayVal) {month = monthVal; day = dayVal; } void input(int m, int d) {month = m; day = d;} public void output() { System.out.println(“month=“ +month+ ”, day=“ +day); } int month, day; } package Two; public class TestDemo { public static void main() { DayOfYear date1(3,18), examdate(); System.out.print(“date1.month=“ +date1.month+ ”, date1.day=“ +date1.day); examdate.input(3,20); examdate.output(); } Compiling error! Why? Default access is “package access!” How to create objects?

One Example public class DayOfYear { public DayOfYear() {} public DayOfYear(int monthVal, int dayVal) {month = monthVal; day = dayVal; } void input(int m, int d) {month = m; day = d;} public void output() { System.out.println(“month=“ +month+ ”, day=“ +day); } private int month=1, day=1; } public class TestDemo { public static void main() { DayOfYear date1, examdate; date1=new DayOfYear(); examdate=new DayOfYear(); date1.output(); examdate.input(3,20); examdate.output(); } How about this example?

Constructor Do you know the role of constructor? When will a constructor be called? When will an object be created? How many constructors can a class have? Do you need a destructor in Java?

Exercise YourClass anObject = new YourClass(42, 'A'); YourClass anotherObject = new YourClass(); anotherObject.doStuff(); YourClass oneMoreObject; oneMoreObject.doStuff(); oneMoreObject.YourClass(99, 'B'); public class YourClass { private int information = 0; private char moreInformation = ‘’; public YourClass( int newInfo, char moreNewInfo) { } public void doStuff() { } } Given the following definition Which of the following are legal?

Exercise YourClass anObject = new YourClass(42, 'A'); YourClass anotherObject = new YourClass(); anotherObject.doStuff(); YourClass oneMoreObject; oneMoreObject.doStuff(); oneMoreObject.YourClass(99, 'B'); public class YourClass { private int information = 0; private char moreInformation = ‘’; public YourClass( int newInfo, char moreNewInfo) { } public void doStuff() { } } Given the following definition Which of the following are legal?

Java Inheritance Inheritance is one of the main techniques of object- oriented programming (OOP). It enables potentially infinite reuse of resources. It can be used to enhance and improve the previous programs for the changing requirements In one sentence, inheritance allows us to create new class from the existing classes without doing much repeated work.

Java Inheritance public class Employee { public // constructor list public // member functions private string name, ssn; private double netPay; } public class HourlyEmployee extends Employee { public // constructor list // new member functions private double wageRate; private double hours; }

Java Inheritance The phrase extends BaseClass must be added to the derived class definition. The derived class inherits all the public methods, all the public and private instance variables, and all the public and private static variables from the base class. The code is reused without having to explicitly copy it, unless the creator of the derived class redefines one or more of the base class methods The derived class can add more instance variables, static variables, and/or methods

Overriding a method Can the return type of the overriding method be modified? public class Base { public Employee func() { … return Employee(); } private int val1; private string val2; } public class Derived extends Base { public HourlyEmployee func() { …… return HourlyEmployee(); } private int val3; private double val4; } Can we change the access modifier of a method? Need to have the same function signatures!

Overriding a method Can the return type of the overriding method be modified? public class Base { public Employee func() { … return Employee(); } private int val1; private string val2; } public class Derived extends Base { public HourlyEmployee func() { …… return HourlyEmployee(); } private int val3; private double val4; } Typically no! But it is allowed if the derived class has the return type which is the derived class of the return type of the original function! Can we change the access modifier of a method? Need to have the same function signatures! Yes, but can only weaken the control.

Constructor in derived classes What do we need to pay attentions to ? We need to properly initialize the member variables inherited from the base class

Constructor in derived classes What do we need to pay attentions to ? We need to properly initialize the member variables inherited from the base class How? Use key word super(…) to call the corresponding constructor of the base class. super(…) should always be the first line. public class Base { public Base() { val1= 0; val2 = “”; } public int val1; private string val2; } public class Derived extends Base { public Derived() { super(); val1 = 0; val4 = 0.0; } public int val1; private double val4; }

An example on super constructor public class Base { private int x, y = 0; public Base(int x_val, int y_val) { x = x_val; y = y_val; } public Base(int x_val) { this (x_val); } …… } The base class public class Derived extends Base { private double x, y = 0; public Derived(double x_val, double y_val) { x = x_val; y = y_val; } public Derived(double x_val) { this (x_val, 0.0); x = x_val; super (x_val); } …… } The derived class Any issues?

An example on super constructor public class Base { private int x, y = 0; public Base(int x_val, int y_val) { x = x_val; y = y_val; } public Base(int x_val) { this (x_val); } …… } The base class public class Derived extends Base { private double x, y = 0; public Derived(double x_val, double y_val) { // Base class does not have a constructor with empty argument list! x = x_val; y = y_val; } public Derived(double x_val) { this (x_val, 0.0); x = x_val; super (x_val); // super needs to be in the first line! } …… } The derived class Any issues?

An example on super constructor public class Base { private int x = 0, y = 0; public Base() {} public Base(int x_val, int y_val) { x = x_val; y = y_val; } public Base(int x_val) { this (x_val); } …… } The base class public class Derived extends Base { private double x, y = 0; public Derived(double x_val, double y_val) { super (x_val); // super needs to be in the first line! x = x_val; y = y_val; } public Derived(double x_val) { this (x_val, 0.0); x = x_val; } …… } The derived class Any issues?

Constructor in derived classes What do we need to pay attentions to ? We need to properly initialize the member variables inherited from the base class How? Use key word super(…) to call the corresponding constructor of the base class. super(…) should always be the first line. Do you know the difference between super(…) and this(…)? Do you know how to use super. to invoke the overridden function from the base class?

Example public class Base { protected int x=0, y=0; public Base(int x_val, int y_val) { x = x_val; y = y_val; System.out.println(“Base class.”); } public Base() { this (0, 0); } public void print() { System.out.println(“x=“+x); System.out.println(“y=“+y); } public class Derived extends Base { protected double x=0, y=0; public Derived() { this (0.0, 1.0); } public Derived(double x_val, double y_val) { super ((int)x_val, (int)y_val); x = x_val; y = y_val; System.out.println(“Derived class.”); } public class Derived2 extends Derived { boolean setx_or_y = false; public Derived2(){} public Derived2(boolean flag, double val) { if (flag==true) x=val; else y=val; setx_or_y = flag; System.out.println("Derived class 2."); } public static void main(String[] args) { Base obj1; Derived obj2 = new Derived (4, 5); Derived2 obj3 = new Derived2(false, 3); obj2.print(); obj3.print(); } what will be the output?

Example public class Base { protected int x=0, y=0; public Base(int x_val, int y_val) { x = x_val; y = y_val; System.out.println(“Base class.”); } public Base() { this (0, 0); } public void print() { System.out.println(“x=“+x); System.out.println(“y=“+y); } public class Derived extends Base { protected double x=0, y=0; public Derived() { this (0.0, 1.0); } public Derived(double x_val, double y_val) { super ((int)x_val, (int)y_val); x = x_val; y = y_val; System.out.println(“Derived class.”); } public class Derived2 extends Derived { boolean setx_or_y = false; public Derived2(){} public Derived2(boolean flag, double val) { if (flag==true) x=val; else y=val; setx_or_y = flag; System.out.println("Derived class 2."); } public static void main(String[] args) { Base obj1; Derived obj2 = new Derived (4, 5); Derived2 obj3 = new Derived2(false, 3); obj2.print(); obj3.print(); } Base Derived Derived2

Example public class Base { protected int x=0, y=0; public Base(int x_val, int y_val) { x = x_val; y = y_val; System.out.println(“Base class.”); } public Base() { this (0, 0); } public void print() { System.out.println(“x=“+x); System.out.println(“y=“+y); } public class Derived extends Base { protected double x=0, y=0; public Derived() { this (0.0, 1.0); } public Derived(double x_val, double y_val) { super ((int)x_val, (int)y_val); x = x_val; y = y_val; System.out.println(“Derived class.”); } public class Derived2 extends Derived { boolean setx_or_y = false; public Derived2(){} public Derived2(boolean flag, double val) { if (flag==true) x=val; else y=val; setx_or_y = flag; System.out.println("Derived class 2."); } public static void main(String[] args) { Base obj1; Derived obj2 = new Derived (4, 5); Derived2 obj3 = new Derived2(false, 3); obj2.print(); obj3.print(); } Base Derived Derived2 Base class. Derived class.

Example public class Base { protected int x=0, y=0; public Base(int x_val, int y_val) { x = x_val; y = y_val; System.out.println(“Base class.”); } public Base() { this (0, 0); } public void print() { System.out.println(“x=“+x); System.out.println(“y=“+y); } public class Derived extends Base { protected double x=0, y=0; public Derived() { this (0.0, 1.0); } public Derived(double x_val, double y_val) { super ((int)x_val, (int)y_val); x = x_val; y = y_val; System.out.println(“Derived class.”); } public class Derived2 extends Derived { boolean setx_or_y = false; public Derived2(){} public Derived2(boolean flag, double val) { if (flag==true) x=val; else y=val; setx_or_y = flag; System.out.println("Derived class 2."); } public static void main(String[] args) { Base obj1; Derived obj2 = new Derived (4, 5); Derived2 obj3 = new Derived2(false, 3); obj2.print(); obj3.print(); } Base Derived Derived2 Base class. Derived class.

Example public class Base { protected int x=0, y=0; public Base(int x_val, int y_val) { x = x_val; y = y_val; System.out.println(“Base class.”); } public Base() { this (0, 0); } public void print() { System.out.println(“x=“+x); System.out.println(“y=“+y); } public class Derived extends Base { protected double x=0, y=0; public Derived() { this (0.0, 1.0); } public Derived(double x_val, double y_val) { super ((int)x_val, (int)y_val); x = x_val; y = y_val; System.out.println(“Derived class.”); } public class Derived2 extends Derived { boolean setx_or_y = false; public Derived2(){} public Derived2(boolean flag, double val) { if (flag==true) x=val; else y=val; setx_or_y = flag; System.out.println("Derived class 2."); } public static void main(String[] args) { Base obj1; Derived obj2 = new Derived (4, 5); Derived2 obj3 = new Derived2(false, 3); obj2.print(); obj3.print(); } Base Derived Derived2 Base class. Derived class. Base class. Derived class. Derived class 2.

Example public class Base { protected int x=0, y=0; public Base(int x_val, int y_val) { x = x_val; y = y_val; System.out.println(“Base class.”); } public Base() { this (0, 0); } public void print() { System.out.println(“x=“+x); System.out.println(“y=“+y); } public class Derived extends Base { protected double x=0, y=0; public Derived() { this (0.0, 1.0); } public Derived(double x_val, double y_val) { super ((int)x_val, (int)y_val); x = x_val; y = y_val; System.out.println(“Derived class.”); } public class Derived2 extends Derived { boolean setx_or_y = false; public Derived2(){} public Derived2(boolean flag, double val) { if (flag==true) x=val; else y=val; setx_or_y = flag; System.out.println("Derived class 2."); } public static void main(String[] args) { Base obj1; Derived obj2 = new Derived (4, 5); Derived2 obj3 = new Derived2(false, 3); obj2.print(); obj3.print(); } Base Derived Derived2 Base class. Derived class. Base class. Derived class. Derived class 2.

Example public class Base { protected int x=0, y=0; public Base(int x_val, int y_val) { x = x_val; y = y_val; System.out.println(“Base class.”); } public Base() { this (0, 0); } public void print() { System.out.println(“x=“+x); System.out.println(“y=“+y); } public class Derived extends Base { protected double x=0, y=0; public Derived() { this (0.0, 1.0); } public Derived(double x_val, double y_val) { super ((int)x_val, (int)y_val); x = x_val; y = y_val; System.out.println(“Derived class.”); } public class Derived2 extends Derived { boolean setx_or_y = false; public Derived2(){} public Derived2(boolean flag, double val) { if (flag==true) x=val; else y=val; setx_or_y = flag; System.out.println("Derived class 2."); } public static void main(String[] args) { Base obj1; Derived obj2 = new Derived (4, 5); Derived2 obj3 = new Derived2(false, 3); obj2.print(); obj3.print(); } Base Derived Derived2 Base class. Derived class. Base class. Derived class. Derived class 2. x=4 y=5 x=0 y=1

Take Home Example public class Base1 { public Base1(int val) { System.out.println(“Base1: “+val); } public class Derived11 extends Base1 { public Derived11 (int val) { super(val); System.out.println(“Derived11: “+val); } public class Derived12 extends Derived11 { public Derived12 (int val) { super(val); System.out.println(“Derived12: “+val); } public class Base2 { public Base2(int val) { System.out.println(“Base2: “+val); } public class Derived21 extends Base2 { public Derived21 (int val) { super(val); System.out.println(“Derived21: “+val); } public class Derived31 extends Base3 { private Derived11 comp1; private Derived21 comp2; public Derived31(int val) { super(val+1); comp1 = new Derived12(val+2); comp2 = new Derived21(val+4); } public static void main(String[] args) { Derived31 obj = new Derived31(1); } public class Base3 { public Base3(int val) { System.out.println(“Base3: “+val); }

Java Polymorphism Why do we need polymorphism. – Further improve the reuse and maintenance of software What does polymorphism mean? – It refers to the ability to associate many meanings to one method name by means of a special mechanism known as late binding or dynamic binding. – What does late binding mean? determining the instance function based on the type of the calling object during run time!

Java Polymorphism How to enable late binding in Java? What are the three ingredients to enable Java polymorphism?

Java Polymorphism How to enable late binding in Java? – Most functions are late binding What are the three ingredients to enable Java polymorphism? – Inheritance – method overriding – upcasting

Example public class Animal { public Animal() { System.out.println(“Animal.”);} public void eat() { System.out.println(“Animal needs to eat.”); } } public class Bird extends Animal { public Bird () { System.out.println(“Bird.”);} public void eat() { System.out.println(“Bird eats bugs.”); } } public class Human extends Primate { public Human() { System.out.println(“Human.”);} public void eat() { System.out.println(“Human eats whatever we can eat.”); } } public class Primate extends Animal { public Primate() { System.out.println(“Primate.”);} public void eat() { System.out.println(“Primate eats both vegs and meat.”); } } public class WhatAnimalEat { public static void whatdoyoueat(Animal a) { a.eat(); } public static void main(String[] args) { Animal a, b, c; a = new Animal(); b = new Bird(); c = new Human(); whatdoyoueat(a); whatdoyoueat(b); whatdoyoueat(c); } What will be the output?

The final Modifier If the modifier final is placed before the definition of a method, then that method may not be redefined in a derived class If the modifier final is placed before the definition of a class, then that class may not be used as a base class to derive other classes

Example public class Animal { public Animal() { System.out.println(“Animal.”);} public void eat() { System.out.println(“Animal needs to eat.”); } } public class Bird extends Animal { public Bird () { System.out.println(“Bird.”);} public void eat() { System.out.println(“Bird eats bugs.”); } } public class Human extends Primate { public Human() { System.out.println(“Human.”);} } public class Primate extends Animal { public Primate() { System.out.println(“Primate.”);} public final void eat() { System.out.println(“Primate eats both vegs and meat.”); } } public class WhatAnimalEat { public static void whatdoyoueat(Animal a) { a.eat(); } public static void main(String[] args) { Animal a, b, c; a = new Animal(); b = new Bird(); c = new Human(); whatdoyoueat(a); whatdoyoueat(b); whatdoyoueat(c); } What will be the output?

Abstract Class To postpone the definition of a method, it is specified as an abstract method. public abstract class Figure { public Figure (double cx, double cy) { center_x=cx; center_y=cy;} public Figure() { this (0,0); } public abstract void draw(); public abstract void area(); public void reset_center(double x, double y) { center_x=x; center_y=y;} private double center_x=0, center_y=0; }; Abstract methods define the interface of the base class and all its derived classes, because…? An abstract class must have the “abstract” modifier in its class heading A class containing at least one abstract method needs to be specified as an abstract class.

Abstract Class To postpone the definition of a method, it is specified as an abstract method. public abstract class Figure { public Figure (double cx, double cy) { center_x=cx; center_y=cy;} public Figure() { this (0,0); } public abstract void draw(); public abstract void area(); public void reset_center(double x, double y) { center_x=x; center_y=y;} private double center_x=0, center_y=0; }; Abstract methods define the interface of the base class and all its derived classes, because…? An abstract class must have the “abstract” modifier in its class heading A class containing at least one abstract method needs to be specified as an abstract class. Can an abstract class be used to create an object? Why or why not?

Example public abstract class Base { protected int type = 0; public Base(int type) { type = type; System.out.println(“Base class.”); } public Base() { this (0); } public abstract int getType() { return type;} public String toString() { return Integer.toString(getType()); } public class Derived extends Base { private int derived_type = 1; public Derived (int type) { super (type); derived_type=type; System.out.println(“Derived class.”); } public Derived() { this(1); } public int getType() { System.out.print(“Derived class type ”); return derived_type ; } public class TestDemo { public static void main(String[] args) { Base obj1 = new Derived(1); Base obj2 = new Base(); Base obj3 = new Derived2(3) System.out.println(obj1); System.out.println(obj2); System.out.println(obj3); } public class Derived2 extends Derived { private int derived_type = 2; public Derived2 (int type) { super (type); derived_type=type; System.out.println(“Derived class 2.”); } public Derived2() { this(2);} public int getType() { System.out.print(“Derived class 2 type ”); return type; } What will be the output of this code?

Java Interface A Java interface specifies a set of methods that any class that implements the interface must have. One way to view an interface is as an extreme form of an abstract class. An interface is NOT a class, but rather a type! Purpose: define methods with parameters of an interface type, and have the code apply to all classes that implements the interface.

Java Interface A Java interface specifies a set of methods that any class that implements the interface must have. One way to view an interface is as an extreme form of an abstract class. An interface is NOT a class, but rather a type! Purpose: define methods with parameters of an interface type, and have the code apply to all classes that implement the interface. public interface Interface_Name { public return_type func1( ); public void func2(); public String getInfo(); public boolean compareTwoObjs(Object obj1, Object obj2); } public for the interface methods!

Java Interface A Java interface specifies a set of methods that any class that implements the interface must have. One way to view an interface is as an extreme form of an abstract class. An interface is NOT a class, but rather a type! Purpose: define methods with parameters of an interface type, and have the code apply to all classes that implement the interface. public interface Interface_Name { public return_type func1(…) public void func2(); public String getInfo(); } Other classes that use the interface need to use the key word implements. public ConcreteClass implements Interface_Name { public Object func1(…){//provide func body!} public void func2(){ // func2 body} public String getInfo(){ // getInfo body} }