Introduction to Java for C/C++ Programmers. Kevin Squire Department of Computer Science Naval Postgraduate School
|
|
- Nickolas Logan
- 6 years ago
- Views:
Transcription
1 Introduction to Java for C/C++ Programmers Kevin Squire Department of Computer Science Naval Postgraduate School
2 Homework Download and install Java 6.0 Eclipse I ll introduce Eclipse sometime this week 2
3 The First Program class Hello { // main: generate some simple output public static void main (String[] args) { System.out.println ("Hello, world."); // Save as Hello.java // Compile with javac Hello.java // Run with java Hello 3
4 The First Program class CLASSNAME { public static void main (String[] args) { STATEMENTS 4
5 Variables and Types Some types are the same as C int hour, minute; float temperature; Some (e.g., Strings) are (somewhat) new: String firstname; String lastname; 5
6 Printing Variables class Hello { public static void main (String[] args) { String firstline; firstline = "Hello, again!"; System.out.println (firstline); 6
7 Operators Mostly the same int hour, minute; hour = 11; minute = 59; System.out.print ("Number of minutes since midnight: "); System.out.println (hour*60 + minute); System.out.print ("Fraction of the hour that has passed: "); System.out.println (minute/60); 7
8 Operators for Strings Some new: int i = 5; String hello = "" + i + " Hello, " + "world."; puts the following string in the variable hello "5 Hello, world." 8
9 Math Methods (Functions) import static java.lang.math.sqrt; double root = sqrt (17.0); double angle = 1.5; double height = Math.sin (angle); double degrees = 90; double angle = degrees * 2 * Math.PI / 360.0; int x = (int)math.round (Math.PI * 20.0); double x = Math.exp (Math.log (10.0)); 9
10 static keyword In addition to (instance) members, a Java class can include static members that are attached to the class rather than instances of the class. Equivalent to C/C++ functions which are not class methods Since they are not attached to objects, they do not have access to any particular object s data members All Math functions (Math.sin, Math.sqrt, etc.) are static member functions of the Math class. 10
11 Defining New Static Methods Form: public static void NAME ( LIST OF PARAMETERS ) { STATEMENTS Example public static void newline () { System.out.println (""); 11
12 Class With Only static Methods class NewLine { public static void newline () { System.out.println (""); public static void threeline () { newline (); newline (); newline (); public static void main (String[] args) { System.out.println ("First line."); threeline (); System.out.println ("Second line."); 12
13 String Objects Java has two kinds of variables: primitive types objects Strings are the only object type we've talked about so far Questions we might ask: What is the data contained in a String object? What are the methods we can invoke on String objects? 13
14 Aside: Java Documentation All Java documentation is downloadable or available online. Try: search Google for java 5.0 String 14
15 Reminder: chars char fred = c ; if (fred == c ) { System.out.println (fred); 15
16 String charat method The following code: String fruit = "banana"; char letter = fruit.charat(1); System.out.println (letter); yields a Why? 16
17 String charat method The following code: String fruit = "banana"; char letter = fruit.charat(1); System.out.println (letter); yields a Why? To get the first letter, use char letter = fruit.charat(0); 17
18 Length What's wrong with the statements below? int length = fruit.length(); char last = fruit.charat (length); 18
19 Length What's wrong with the statements below? int length = fruit.length(); char last = fruit.charat (length); Correct version: int length = fruit.length(); char last = fruit.charat (length-1); 19
20 Indices String fruit = "banana"; int index = fruit.indexof( a ); int index = fruit.indexof( a, 2); // start at // position 2 20
21 Other Notes on Strings Strings are immutable Strings are not comparable with ==, >, etc. 21
22 Comparing Strings String name1 = "Alan Turing"; String name2 = "Ada Lovelace"; if (name1.equals (name2)) { System.out.println ("The names are the same."); int flag = name1.compareto (name2); if (flag == 0) { System.out.println ("The names are the same."); else if (flag < 0) { System.out.println ("name1 comes before name2."); else if (flag > 0) { System.out.println ("name2 comes before name1."); 22
23 Interesting Objects Packages Contain built-in Java classes java.lang is available by default (includes all of the basic parts of the language) Must be imported, e.g. import java.awt.*; imports all classes in the java.awt package. 23
24 Point Objects import java.awt.*; // goes at top of file, outside main()... Point blank; blank = new Point (3, 4); Rectangle box = new Rectangle (0, 0, 100, 200); // Access coordinate of blank int x = blank.x; System.out.println (blank.x + ", " + blank.y); int distance = blank.x * blank.x + blank.y * blank.y; 24
25 Objects as Parameters public static void printpoint (Point p) { System.out.println ("(" + p.x + ", " + p.y + ")"); // System.out.println(blank) gives: java.awt.point[x=3,y=4] public static double distance (Point p1, Point p2) { double dx = (double)(p2.x - p1.x); double dy = (double)(p2.y - p1.y); return Math.sqrt (dx*dx + dy*dy); 25
26 Objects as Return Types public static Point findcenter (Rectangle box) { int x = box.x + box.width/2; int y = box.y + box.height/2; return new Point (x, y); 26
27 Objects are Mutable public static void moverect (Rectangle box, int dx, int dy) { box.x = box.x + dx; box.y = box.y + dy;... Rectangle box = new Rectangle (0, 0, 100, 200); moverect (box, 50, 100); System.out.println (box); // yields java.awt.rectangle[x=50,y=100,width=100,height=200] 27
28 Aliasing/References Rectangle box1 = new Rectangle (0, 0, 100, 200); Rectangle box2 = box1; box1 and box2 both refer to the same Rectangle. Alternatively, we can say that the given Rectangle has two aliases (box1 and box2) 28
29 null When you create an object variable, remember that you are creating a reference to an object. Until you make the variable point to an object, the value of the variable is null. null is a special value in Java (and a Java keyword) that is used to mean no object. The declaration Point blank; is equivalent to the initialization Point blank = null; 29
30 Null Pointer Exceptions Point blank = null; int x = blank.x; blank.translate (50, 50); // NullPointerException // NullPointerException 30
31 Garbage Collection Create a new Point: Point blank = new Point (3, 4); Set blank to null: blank = null; In C, this would cause a memory leak; the memory allocated in the first statement would be lost until the program exits. In contrast, Java keeps track of the memory allocated to the object, and reclaims it (deallocates it) when there are no more references to the object There is therefore no need for delete in Java (and it doesn t exist). 31
32 Creating Your Own Classes Defining classes in Java is slightly different than in C++ By convention, class names (and hence object types) always begin with a capital letter, which helps distinguish them from primitive types and variable names. You usually put one class definition in each file, and the name of the file must be the same as the name of the class, with the suffix.java. For example, the Time class is defined in the file named Time.java. In any program, one class is designated as the startup class. The startup class must contain a method named main, which is where the execution of the program begins. Other classes may have a method named main, but it will not be executed. Basic differences between Java and C++ class definition are highlighted on the following slides. 32
33 C++/Java Class Definition C++: Java: class CRectangle { int width, height; public: CRectangle (int, int); int area () { return (width*height); ; CRectangle::CRectangle (int a, int b) { width = a; height = b; public class CRectangle { private int width, height; public CRectangle (int a, int b) { width = a; height = b; public int area () { return (width*height); 33
34 C++/Java Class Definition C++: Java: class CRectangle { int width, height; public: CRectangle (int, int); int area () { return (width*height); ; // Note: ";" required here CRectangle::CRectangle (int a, int b) { width = a; height = b; public class CRectangle { private int width, height; public CRectangle (int a, int b) { width = a; height = b; public int area () { return (width*height); // Note: no ";" required here 34
35 C++/Java Class Definition C++: Java: class CRectangle { int width, height; public: CRectangle (int, int); int area () { return (width*height); ; CRectangle::CRectangle (int a, int b) { width = a; height = b; public class CRectangle { private int width, height; public CRectangle (int a, int b) { width = a; height = b; public int area () { return (width*height); 35
36 C++/Java Class Definition C++: Java: class CRectangle { int width, height; public: CRectangle (int, int); int area () { return (width*height); ; CRectangle::CRectangle (int a, int b) { width = a; height = b; public class CRectangle { private int width, height; public CRectangle (int a, int b) { width = a; height = b; public int area () { return (width*height); 36
37 C++/Java Class Definition C++: Java: public class CRectangle {... int main () { public static void main(string [] args) { CRectangle recta (3,4); CRectangle rectb (5,6); cout << "recta area: " << recta.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; CRectangle recta = new CRectangle (3,4); CRectangle rectb = new CRectangle (5,6); System.out.println( "recta area: " + recta.area()); System.out.println( "rectb area: " + rectb.area()); 37
38 C++/Java Class Definition C++: Java: public class CRectangle { // main is... // inside a class def. int main () { public static void main(string [] args) { CRectangle recta (3,4); CRectangle rectb (5,6); cout << "recta area: " << recta.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; CRectangle recta = new CRectangle (3,4); CRectangle rectb = new CRectangle (5,6); System.out.println( "recta area: " + recta.area()); System.out.println( "rectb area: " + rectb.area()); 38
39 C++/Java Class Definition C++: int main () { Java: public class CRectangle {... // main() s type is different public static void main(string [] args) { CRectangle recta (3,4); CRectangle rectb (5,6); cout << "recta area: " << recta.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; CRectangle recta = new CRectangle (3,4); CRectangle rectb = new CRectangle (5,6); System.out.println( "recta area: " + recta.area()); System.out.println( "rectb area: " + rectb.area()); 39
40 C++/Java Class Definition Function overloading is the same as C++ Destructors are the same (~ClassName()), but are not needed as frequently (why?) 40
41 Inheritance and Polymorphism Inheritance and Polymorphism are very similar in Java and C++ To derive a subclass, the notation is class SUBCLASS extends SUPERCLASS { The constructor of the superclass is accessed via a call to the function super(). Note that all methods are virtual by default So, if a subclass overrides a method of a parent class, the right method will always be called 41
42 Code Example C++: Java: #include <iostream> using namespace std; class CPolygon { protected: int width, height; public: CPolygon(int a, int b) { width=a; height=b; virtual int area() {return 0; ; class CRectangle: public CPolygon { public: CRectangle(int a, int b): CPolygon(a,b) { In file Polygon.java: public class Polygon { protected int width, height; public Polygon(int a, int b) { width=a; height=b; public int area() {return 0; In file Rectangle.java: public class Rectangle extends Polygon{ public Rectangle(int a, int b) { super(a,b); int area () { return (width * height); ; public int area () { return (width * height); 42
43 Code Example C++: Java: #include <iostream> using namespace std; class CPolygon { protected: int width, height; public: CPolygon(int a, int b) { width=a; height=b; virtual int area() {return 0; ; class CRectangle: public CPolygon { public: CRectangle(int a, int b): CPolygon(a,b) { In file Polygon.java: public class Polygon { protected int width, height; public Polygon(int a, int b) { width=a; height=b; public int area() {return 0; In file Rectangle.java: public class Rectangle extends Polygon{ public Rectangle(int a, int b) { super(a,b); int area () { return (width * height); ; public int area () { return (width * height); 43
44 Code Example C++: Java: #include <iostream> using namespace std; class CPolygon { protected: int width, height; public: CPolygon(int a, int b) { width=a; height=b; virtual int area() {return 0; ; class CRectangle: public CPolygon { public: CRectangle(int a, int b): CPolygon(a,b) { In file Polygon.java: public class Polygon { protected int width, height; public Polygon(int a, int b) { width=a; height=b; public int area() {return 0; In file Rectangle.java: public class Rectangle extends Polygon{ public Rectangle(int a, int b) { super(a,b); int area () { return (width * height); ; public int area () { return (width * height); 44
45 Code Example C++: Java: #include <iostream> using namespace std; class CPolygon { protected: int width, height; public: CPolygon(int a, int b) { width=a; height=b; virtual int area() {return 0; ; class CRectangle: public CPolygon { public: CRectangle(int a, int b): CPolygon(a,b) { In file Polygon.java: public class Polygon { protected int width, height; public Polygon(int a, int b) { width=a; height=b; public int area() {return 0; In file Rectangle.java: public class Rectangle extends Polygon{ public Rectangle(int a, int b) { super(a,b); int area () { return (width * height); ; public int area () { return (width * height); 45
46 Code Example (cont.) C++: Java: In file Triangle.java: class CTriangle: public CPolygon { public: CTriangle(int a, int b): CPolygon(a,b) { int area () { return (width * height / 2); ; public class Triangle extends Polygon { public Triangle(int a, int b) { super(a,b); public int area () { return (width * height / 2); int main () { CRectangle rect(4,5); CTriangle trgl(4,5); cout << rect.area() << endl; cout << trgl.area() << endl; return 0; In file PolyTest.java: public class PolyTest { public static void int main () { Rectangle rect = new Rectangle(4,5); Triangle trgl = new Triangle(4,5); System.out.println(rect.area()); System.out.println(trgl.area()); 46
47 Code Example (cont.) C++: Java: In file Triangle.java: class CTriangle: public CPolygon { public: CTriangle(int a, int b): CPolygon(a,b) { int area () { return (width * height / 2); ; public class Triangle extends Polygon { public Triangle(int a, int b) { super(a,b); public int area () { return (width * height / 2); int main () { CRectangle rect(4,5); CTriangle trgl(4,5); cout << rect.area() << endl; cout << trgl.area() << endl; return 0; In file PolyTest.java: public class PolyTest { public static void int main () { Rectangle rect = new Rectangle(4,5); Triangle trgl = new Triangle(4,5); System.out.println(rect.area()); System.out.println(trgl.area()); 47
48 Code Example (cont.) C++: Java: In file Triangle.java: class CTriangle: public CPolygon { public: CTriangle(int a, int b): CPolygon(a,b) { int area () { return (width * height / 2); ; public class Triangle extends Polygon { public Triangle(int a, int b) { super(a,b); public int area () { return (width * height / 2); int main () { CRectangle rect(4,5); CTriangle trgl(4,5); cout << rect.area() << endl; cout << trgl.area() << endl; return 0; In file PolyTest.java: public class PolyTest { public static void int main () { Rectangle rect = new Rectangle(4,5); Triangle trgl = new Triangle(4,5); System.out.println(rect.area()); System.out.println(trgl.area()); 48
49 Polymorphism Example (cont.) C++: Java: In file Triangle.java: class CTriangle: public CPolygon { public: CTriangle(int a, int b): CPolygon(a,b) { int area () { return (width * height / 2); ; int main () { CPolygon *rect = new CRectangle(4,5); CPolygon *trgl = new CTriangle(4,5); cout << rect->area() << endl; cout << trgl->area() << endl; return 0; public class Triangle extends Polygon { public Triangle(int a, int b) { super(a,b); public int area () { return (width * height / 2); In file PolyTest.java: public class PolyTest { public static void int main () { Polygon rect = new Rectangle(4,5); Polygon trgl = new Triangle(4,5); System.out.println(rect.area()); System.out.println(trgl.area()); 49
50 C++ Pure Virtual Classes = Java Abstract Classes C++: #include <iostream> using namespace std; class CPolygon { protected: int width, height; public: CPolygon(int a, int b) { width=a; height=b; virtual int area() = 0; ;... int main () { CPolygon *rect = new CRectangle(4,5); CPolygon *trgl = new CTriangle(4,5); // illegal //CPolygon *poly = new CPolygon(4,5); cout << rect->area() << endl; cout << trgl->area() << endl; //cout << poly->area() << endl; return 0; Java: In file Polygon.java: public abstract class Polygon { protected int width, height; public Polygon(int a, int b) { width=a; height=b; public abstract int area();... In file PolyTest.java: public class PolyTest { public static void int main () { Polygon rect = new Rectangle(4,5); Polygon trgl = new Triangle(4,5); // illegal // Polygon poly = new Polygon(4,5); System.out.println(rect.area()); System.out.println(trgl.area()); // System.out.println(poly.area()); 50
51 Class Object In Java, all classes (built-in and user-defined) are subclasses or descendents of class Object. You ll notice this fact when using the online Java documentation Because of this, every class inherits a number of useful standard methods from class Object, including: tostring(), equal(), hashcode() It is often useful or necessary to override these methods. 51
52 Numerical Object Types For each primitive type in Java, there is a corresponding Object type Sometimes Object types are required when using built-in classes (e.g., ArrayList) Easy to convert between the two (just assign one to the other) Note on 8-bit types char is a character type in Java byte is an 8-bit numerical type in Java These are not equivalent Primitive Type char boolean byte int short long float double Object Type Character Boolean Byte Integer Short Long Float Double 52
53 Additional Type Notes All Java types are signed The following are illegal in Java: unsigned long biglong; unsigned double salary; // not legal in Java // not legal in Java The boolean type in Java is called boolean (cf. bool in C++) true and false are NOT equal to 1 and 0, as they are in C++ Casting between boolean and int types is not allowed: boolean abool = false; int anint = (int)abool; // not legal in Java // not legal in Java 53
54 Java Interfaces An interface in Java is a collection of method declarations and constants, with no data and no bodies. We say that a class implements an interface if it implements all of the methods declared in the interface. In general, interfaces define behaviors we desire in a wide variety of possibly unrelated classes. 54
55 Interface Example As an example, consider an interface for objects that can be sold: public interface Sellable { public String description(); public int listprice(); public int lowestprice(); Any class which implements this interface must define these three functions. 55
56 Interface Example Here's a class which implements Sellable: public class Photograph implements Sellable { private String descript; private int price; private boolean color; public Photograph(String desc, int p, boolean c) { descript = desc; price = p; color = c; public String description() { return descript; public int listprice() { return price; public int lowestprice() { return price/2; public boolean iscolor() { return color; 56
57 Interface Example Suppose we had another interface, Transportable: public interface Transportable { /** weight in grams */ public int weight(); /** whether the object is hazardous */ public boolean ishazardous(); Note that, as before, the interface defines no code, only function prototypes. 57
58 Multiple Inheritance We can then create a class which implements both interfaces. This is called multiple inheritance. public class BoxedItem implements Sellable, Transportable {... public String description() { return descript; public int listprice() { return price; public int lowestprice() { return price/2; public int weight() { return weight; public boolean ishazardous() { return haz; public int insuredvalue() { return price*2;... 58
59 Using Interfaces When using objects which define interfaces, we can treat them very much like classes: Sellable[] itemsforsale = new Sellable[10];... itemsforsale[0] = new Photograph( Monterey Bay, 100, true); itemsforsale[1] = new BoxedItem( TV,...);... System.out.println(itemsForSale[0].description() + : $ + itemsforsale[0].listprice() + +, sale price: + itemsforsale[0].lowestprice(); 59
60 Pre-defined Java Interfaces Java has a large number of useful interfaces predefined, many of which we'll see throughout the quarter Some of them include Comparable: allows objects of an implementing class to be compared and sorted Runnable: used in threads programming Java Collections Framework interfaces, including List: list of items Queue: FIFO list Map: collection of <key,value> pairs Set: collection of objects Collection: any of the above, and more Interfaces used in GUI programming 60
61 Inheritance versus Interface The Java interface is used to share common behavior (only method headers) among the instances of different classes. Inheritance is used to share common code (including both data members and methods) among the instances of related classes. In your program designs, remember to use the Java interface to share common behavior. Use inheritance to share common code. If an entity A is a specialized form of another entity B, then model them by using inheritance. Declare A as a subclass of B. 61
62 C++ Templates Java Generics Java includes a generics framework, similar to C++ Templates, which allows us to define a class in terms of formal type parameters. public class Pair<K,V> {... We instantiate a class using actual type parameters. Pair<String,Integer> pair1 = new Pair<String,Integer>(); 62
63 Generics Example public class Pair<K, V> { private K key; private V value; public void set(k k, V v) { key = k; value = v; public K getkey() { return key; public V getvalue() { return value; public String tostring() { return "[" + getkey() + ", " + getvalue() + "]"; 63
64 Generics Example public static void main (String[] args) { // Create a String-Integer Pair Pair<String,Integer> pair1 = new Pair<String,Integer>(); pair1.set(new String("height"), new Integer(36)); System.out.println(pair1); // Create a Student-Double Pair Pair<Student,Double> pair2 = new Pair<Student,Double>(); pair2.set(new Student("A5976","Sue",19), new Double(9.5)); System.out.println(pair2); 64
65 Generics Example In the previous example, K and V could be instantiated as arbitrary types. We can also restrict their types: public class Pair2<K extends Person, V extends Number> { private K key; private V value;... Generics will be useful for further discussion on lists and other abstract data types (ADTs). 65
66 Eclipse First Run Checklist First run: 1. Select/create a workspace directory (when eclipse starts) 66
67 Eclipse First Run Checklist 1. Change formatting to NOT use tab characters Preferences -> Java -> Code Style -> Formatter For active profile, select Java Conventions [built-in] 67
68 Eclipse First Run Checklist Best: edit this profile, rename it to Java Conventions [spaces only] and select Spaces Only as the Tab policy. 68
69 Eclipse First Run Checklist Make sure JRE is selected Preferences -> Java -> Installed JREs Add a new JRE if necessary 69
70 Eclipse First Run Checklist Make sure JRE is selected Preferences -> Java -> Installed JREs Add a new JRE if necessary 70
71 Eclipse Project Checklist Create a new Java project 71
72 Eclipse Project Checklist Type <Your_Last_Name>_Prog_<x>_<Name> for the project name Select Use project folder as root for sources and class files. Click Finish. 72
73 Eclipse Project Checklist Right click on the new project, and create a new class 73
74 Eclipse Project Checklist For the new class, fill in a package name (same as Project, but first letter should be lower case), class name, and select appropriate options at the bottom. Click Finish. 74
75 Eclipse Project Checklist Your project should look like this. Finish it up and turn it in! 75
Outline. Object-Oriented Design Principles. Object-Oriented Design Goals. What a Subclass Inherits from Its Superclass?
COMP9024: Data Structures and Algorithms Week One: Java Programming Language (II) Hui Wu Session 1, 2014 http://www.cse.unsw.edu.au/~cs9024 Outline Inheritance and Polymorphism Interfaces and Abstract
More informationChapter 1: Object-Oriented Programming Using C++
Chapter 1: Object-Oriented Programming Using C++ Objectives Looking ahead in this chapter, we ll consider: Abstract Data Types Encapsulation Inheritance Pointers Polymorphism Data Structures and Algorithms
More information18. Polymorphism. Object Oriented Programming: Pointers to base class // pointers to base class #include <iostream> using namespace std;
- 126 - Object Oriented Programming: 18. Polymorphism Before getting into this section, it is recommended that you have a proper understanding of pointers and class inheritance. If any of the following
More informationIntroduction Of Classes ( OOPS )
Introduction Of Classes ( OOPS ) Classes (I) A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions. An object is an instantiation of a class.
More informationObject Oriented Programming. A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions.
Classes (I) Object Oriented Programming A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions. An object is an instantiation of a class.
More informationShort Notes of CS201
#includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system
More informationCS201 - Introduction to Programming Glossary By
CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with
More informationData Structures (INE2011)
Data Structures (INE2011) Electronics and Communication Engineering Hanyang University Haewoon Nam ( hnam@hanyang.ac.kr ) Lecture 1 1 Data Structures Data? Songs in a smartphone Photos in a camera Files
More informationProgramming in C++: Assignment Week 5
Programming in C++: Assignment Week 5 Total Marks : 20 Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology Kharagpur 721302 partha.p.das@gmail.com April 3, 2017
More informationData Structures Lecture 2
Fall 2017 Fang Yu Software Security Lab. Dept. Management Information Systems, National Chengchi University Data Structures Lecture 2 Object-oriented Design Abstraction, Modularity, and Encapsulation Abstraction
More informationLab 2 - Introduction to C++
Lab 2 - Introduction to C++ 2.680 Unmanned Marine Vehicle Autonomy, Sensing and Communications February 8th, 2018 Michael Benjamin, mikerb@mit.edu Henrik Schmidt, henrik@mit.edu Department of Mechanical
More informationMidterm Exam 5 April 20, 2015
Midterm Exam 5 April 20, 2015 Name: Section 1: Multiple Choice Questions (24 pts total, 3 pts each) Q1: Which of the following is not a kind of inheritance in C++? a. public. b. private. c. static. d.
More informationInheritance, and Polymorphism.
Inheritance and Polymorphism by Yukong Zhang Object-oriented programming languages are the most widely used modern programming languages. They model programming based on objects which are very close to
More informationClasses: Member functions // classes example #include <iostream> using namespace std; Objects : Reminder. Member functions: Methods.
Classes: Methods, Constructors, Destructors and Assignment For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Piyush Kumar Classes: Member functions // classes
More informationCS2141 Software Development using C/C++ C++ Basics
CS2141 Software Development using C/C++ C++ Basics Integers Basic Types Can be short, long, or just plain int C++ does not define the size of them other than short
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 informationGraphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub
Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java
More informationCS 376b Computer Vision
CS 376b Computer Vision 09 / 25 / 2014 Instructor: Michael Eckmann Today s Topics Questions? / Comments? Enhancing images / masks Cross correlation Convolution C++ Cross-correlation Cross-correlation involves
More informationC++ Quick Guide. Advertisements
C++ Quick Guide Advertisements Previous Page Next Page C++ is a statically typed, compiled, general purpose, case sensitive, free form programming language that supports procedural, object oriented, and
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 informationOutline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring
Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,
More informationNext week s homework. Classes: Member functions. Member functions: Methods. Objects : Reminder. Objects : Reminder 3/6/2017
Next week s homework Classes: Methods, Constructors, Destructors and Assignment Read Chapter 7 Your next quiz will be on Chapter 7 of the textbook For : COP 3330. Object oriented Programming (Using C++)
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 informationPolymorphism CSCI 201 Principles of Software Development
Polymorphism CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D. jeffrey.miller@usc.edu Program Outline USC CSCI 201L Polymorphism Based on the inheritance hierarchy, an object with a compile-time
More informationObject Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.
CMSC 131: Chapter 28 Final Review: What you learned this semester The Big Picture Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. Java
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 informationB2.52-R3: INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING THROUGH JAVA
B2.52-R3: INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING THROUGH JAVA NOTE: 1. There are TWO PARTS in this Module/Paper. PART ONE contains FOUR questions and PART TWO contains FIVE questions. 2. PART ONE
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 C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com
More C++ : Vectors, Classes, Inheritance, Templates with content from cplusplus.com, codeguru.com 2 Vectors vectors in C++ basically arrays with enhancements indexed similarly contiguous memory some changes
More informationPOLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors
POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors CSC 330 OO Software Design 1 Abstract Base Classes class B { // base class virtual void m( ) =0; // pure virtual
More informationPOLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE
Abstract Base Classes POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors class B { // base class virtual void m( ) =0; // pure virtual function class D1 : public
More informationIntroduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1
Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1 Inheritance Consider a new type Square. Following how we declarations for the Rectangle and Circle classes we could declare it as follows:
More informationWeiss Chapter 1 terminology (parenthesized numbers are page numbers)
Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement
More informationFunction Overloading
Function Overloading C++ supports writing more than one function with the same name but different argument lists How does the compiler know which one the programmer is calling? They have different signatures
More information1. Java is a... language. A. moderate typed B. strogly typed C. weakly typed D. none of these. Answer: B
1. Java is a... language. A. moderate typed B. strogly typed C. weakly typed D. none of these 2. How many primitive data types are there in Java? A. 5 B. 6 C. 7 D. 8 3. In Java byte, short, int and long
More informationLecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8
Today... Java basics S. Bowers 1 of 8 Java main method (cont.) In Java, main looks like this: public class HelloWorld { public static void main(string[] args) { System.out.println("Hello World!"); Q: How
More informationMore C++ : Vectors, Classes, Inheritance, Templates
Vectors More C++ : Vectors,, Inheritance, Templates vectors in C++ basically arrays with enhancements indexed similarly contiguous memory some changes defined differently can be resized without explicit
More informationJava Primer. CITS2200 Data Structures and Algorithms. Topic 2
CITS2200 Data Structures and Algorithms Topic 2 Java Primer Review of Java basics Primitive vs Reference Types Classes and Objects Class Hierarchies Interfaces Exceptions Reading: Lambert and Osborne,
More informationAP Computer Science Chapter 10 Implementing and Using Classes Study Guide
AP Computer Science Chapter 10 Implementing and Using Classes Study Guide 1. A class that uses a given class X is called a client of X. 2. Private features of a class can be directly accessed only within
More informationBASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I
BASIC COMPUTATION x public static void main(string [] args) Fundamentals of Computer Science I Outline Using Eclipse Data Types Variables Primitive and Class Data Types Expressions Declaration Assignment
More informationProgram Fundamentals
Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java
More informationJava How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.
Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;
More informationGovernment Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING
Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING THROUGH C++ Practical: OOPS THROUGH C++ Subject Code: 1618407 PROGRAM NO.1 Programming exercise on executing a Basic C++
More informationAssumptions. History
Assumptions A Brief Introduction to Java for C++ Programmers: Part 1 ENGI 5895: Software Design Faculty of Engineering & Applied Science Memorial University of Newfoundland You already know C++ You understand
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 informationCS321 Languages and Compiler Design I. Winter 2012 Lecture 2
CS321 Languages and Compiler Design I Winter 2012 Lecture 2 1 A (RE-)INTRODUCTION TO JAVA FOR C++/C PROGRAMMERS Why Java? Developed by Sun Microsystems (now Oracle) beginning in 1995. Conceived as a better,
More informationFast Introduction to Object Oriented Programming and C++
Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming
More informationCE221 Programming in C++ Part 1 Introduction
CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab
More information! A literal represents a constant value used in a. ! Numbers: 0, 34, , -1.8e12, etc. ! Characters: 'A', 'z', '!', '5', etc.
Week 1: Introduction to C++ Gaddis: Chapter 2 (excluding 2.1, 2.11, 2.14) CS 1428 Fall 2014 Jill Seaman Literals A literal represents a constant value used in a program statement. Numbers: 0, 34, 3.14159,
More informationFunction templates. An abstraction on a function space. A generic type.
Function templates. An abstraction on a function space. A generic type. // function template #include using namespace std; template T Maximum (T, T); main () int i=5, j=86, k; long
More informationclass objects instances Fields Constructors Methods static
Class Structure Classes A class describes a set of objects The objects are called instances of the class A class describes: Fields (instance variables)that hold the data for each object Constructors that
More informationInterview Questions of C++
Interview Questions of C++ Q-1 What is the full form of OOPS? Ans: Object Oriented Programming System. Q-2 What is a class? Ans: Class is a blue print which reflects the entities attributes and actions.
More informationThe C++ Language. Arizona State University 1
The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University
More informationIntroduction to C++ (Extensions to C)
Introduction to C++ (Extensions to C) C is purely procedural, with no objects, classes or inheritance. C++ is a hybrid of C with OOP! The most significant extensions to C are: much stronger type checking.
More informationIntroduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview
Introduction to Visual Basic and Visual C++ Introduction to Java Lesson 13 Overview I154-1-A A @ Peter Lo 2010 1 I154-1-A A @ Peter Lo 2010 2 Overview JDK Editions Before you can write and run the simple
More informationC++ Programming: From Problem Analysis to Program Design, Third Edition
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine
More informationNon-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.
, ean, arithmetic s s on acters Comp Sci 1570 Introduction to C++ Outline s s on acters 1 2 3 4 s s on acters Outline s s on acters 1 2 3 4 s s on acters ASCII s s on acters ASCII s s on acters Type: acter
More informationPIC 20A The Basics of Java
PIC 20A The Basics of Java Ernest Ryu UCLA Mathematics Last edited: November 1, 2017 Outline Variables Control structures classes Compilation final and static modifiers Arrays Examples: String, Math, and
More informationcis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1
topics: introduction to java, part 1 cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 cis20.1-fall2007-sklar-leci.2 1 Java. Java is an object-oriented language: it is
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 informationFall 2017 CISC124 9/16/2017
CISC124 Labs start this week in JEFF 155: Meet your TA. Check out the course web site, if you have not already done so. Watch lecture videos if you need to review anything we have already done. Problems
More informationA Short Summary of Javali
A Short Summary of Javali October 15, 2015 1 Introduction Javali is a simple language based on ideas found in languages like C++ or Java. Its purpose is to serve as the source language for a simple compiler
More informationCS3157: Advanced Programming. Outline
CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching
More informationHomework 6. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine
Homework 6 Yuji Shimojo CMSC 330 Instructor: Prof. Reginald Y. Haseltine July 21, 2013 Question 1 What is the output of the following C++ program? #include #include using namespace
More informationExtending Classes (contd.) (Chapter 15) Questions:
Extending Classes (contd.) (Chapter 15) Questions: 1 1. The following C++ program compiles without any problems. When run, it even prints out the hello called for in line (B) of main. But subsequently
More informationLesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014
Lesson 10A OOP Fundamentals By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Definition Pointers vs containers Object vs primitives Constructors Methods Object class
More informationChapter 1: Introduction to Computers, Programs, and Java
Chapter 1: Introduction to Computers, Programs, and Java 1. Q: When you compile your program, you receive an error as follows: 2. 3. %javac Welcome.java 4. javac not found 5. 6. What is wrong? 7. A: Two
More informationLecture 3. Lecture
True Object-Oriented programming: Dynamic Objects Static Object-Oriented Programming Reference Variables Eckel: 30-31, 41-46, 107-111, 114-115 Riley: 5.1, 5.2 D0010E Object-Oriented Programming and Design
More informationJava. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2)
Summary: Chapters 1 to 10 Sharma Chakravarthy Information Technology Laboratory (IT Lab) Computer Science and Engineering Department The University of Texas at Arlington, Arlington, TX 76019 Email: sharma@cse.uta.edu
More informationProgramming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur
Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture 04 Programs with IO and Loop We will now discuss the module 2,
More informationIST311. Advanced Issues in OOP: Inheritance and Polymorphism
IST311 Advanced Issues in OOP: Inheritance and Polymorphism IST311/602 Cleveland State University Prof. Victor Matos Adapted from: Introduction to Java Programming: Comprehensive Version, Eighth Edition
More information3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal
APCS A Midterm Review You will have a copy of the one page Java Quick Reference sheet. This is the same reference that will be available to you when you take the AP Computer Science exam. 1. n bits can
More informationINHERITANCE. Spring 2019
INHERITANCE Spring 2019 INHERITANCE BASICS Inheritance is a technique that allows one class to be derived from another A derived class inherits all of the data and methods from the original class Suppose
More informationHomework 5. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine
Homework 5 Yuji Shimojo CMSC 330 Instructor: Prof. Reginald Y. Haseltine July 13, 2013 Question 1 Consider the following Java definition of a mutable string class. class MutableString private char[] chars
More informationProgramming Language. Functions. Eng. Anis Nazer First Semester
Programming Language Functions Eng. Anis Nazer First Semester 2016-2017 Definitions Function : a set of statements that are written once, and can be executed upon request Functions are separate entities
More informationObject Oriented Programming 2015/16. Final Exam June 28, 2016
Object Oriented Programming 2015/16 Final Exam June 28, 2016 Directions (read carefully): CLEARLY print your name and ID on every page. The exam contains 8 pages divided into 4 parts. Make sure you have
More informationC++ (classes) Hwansoo Han
C++ (classes) Hwansoo Han Inheritance Relation among classes shape, rectangle, triangle, circle, shape rectangle triangle circle 2 Base Class: shape Members of a class Methods : rotate(), move(), Shape(),
More informationNews and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!
True object-oriented programming: Dynamic Objects Reference Variables D0010E Object-Oriented Programming and Design Lecture 3 Static Object-Oriented Programming UML" knows-about Eckel: 30-31, 41-46, 107-111,
More informationChapter 2. Procedural Programming
Chapter 2 Procedural Programming 2: Preview Basic concepts that are similar in both Java and C++, including: standard data types control structures I/O functions Dynamic memory management, and some basic
More informationCSE 303: Concepts and Tools for Software Development
CSE 303: Concepts and Tools for Software Development Hal Perkins Autumn 2008 Lecture 24 Introduction to C++ CSE303 Autumn 2008, Lecture 24 1 C++ C++ is an enormous language: All of C Classes and objects
More informationIntroduction to C++ Systems Programming
Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions
More informationCS/ENGRD 2110 SPRING Lecture 2: Objects and classes in Java
1 CS/ENGRD 2110 SPRING 2014 Lecture 2: Objects and classes in Java http://courses.cs.cornell.edu/cs2110 Java OO (Object Orientation) 2 Python and Matlab have objects and classes. Strong-typing nature of
More informationCSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington
CSE 333 Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia New exercise posted yesterday afternoon, due Monday morning - Read a directory
More informationChapter 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 informationObjectives. In this chapter, you will:
Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about
More informationCS201- Introduction to Programming Current Quizzes
CS201- Introduction to Programming Current Quizzes Q.1 char name [] = Hello World ; In the above statement, a memory of characters will be allocated 13 11 12 (Ans) Q.2 A function is a block of statements
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 informationInheritance, Polymorphism, and Interfaces
Inheritance, Polymorphism, and Interfaces Chapter 8 Inheritance Basics (ch.8 idea) Inheritance allows programmer to define a general superclass with certain properties (methods, fields/member variables)
More informationContents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance
Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass
More informationSTRUCTURING OF PROGRAM
Unit III MULTIPLE CHOICE QUESTIONS 1. Which of the following is the functionality of Data Abstraction? (a) Reduce Complexity (c) Parallelism Unit III 3.1 (b) Binds together code and data (d) None of the
More informationObjectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program
Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates
More informationChapter 2: Basic Elements of C++
Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates
More information1 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 informationFull file at
Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class
More informationChapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction
Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers
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 informationCS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE
CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE PART A UNIT I 1. Differentiate object oriented programming from procedure oriented programming. 2. Define abstraction and encapsulation. 3. Differentiate
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 informationSubclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented
Table of Contents L01 - Introduction L02 - Strings Some Examples Reserved Characters Operations Immutability Equality Wrappers and Primitives Boxing/Unboxing Boxing Unboxing Formatting L03 - Input and
More informationObject Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia
Object Oriented Programming in Java Jaanus Pöial, PhD Tallinn, Estonia Motivation for Object Oriented Programming Decrease complexity (use layers of abstraction, interfaces, modularity,...) Reuse existing
More information