Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions.

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
Data Structures Lecture 2 Fang Yu Department of Management Information Systems National Chengchi University Fall 2011.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Lecture 2: Object Oriented Programming I
Road Map Introduction to object oriented programming. Classes
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
Scott Grissom, copyright 2004Ch 3: Java Features Slide 1 Why Java? It is object-oriented provides many ready to use classes platform independent modern.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Java CourseWinter 2009/10. Introduction Object oriented, imperative programming language. Developed: Inspired by C++ programming language.
Java Unit 9: Arrays Declaring and Processing Arrays.
OOP Languages: Java vs C++
Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Java and C++, The Difference An introduction Unit - 00.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
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.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
From C++ to Java A whirlwind tour of Java for C++ programmers.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Advanced Java Programming CS 537 – Data Structures and Algorithms.
CS 61B Data Structures and Programming Methodology July 3, 2008 David Sun.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Programming in Java CSCI-2220 Object Oriented Programming.
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
Java Programming Java Basics. Data Types Java has two main categories of data types: –Primitive data types Built in data types Many very similar to C++
CS 11 java track: lecture 2 This week: more on object-oriented programming (OOP) objects vs. primitive types creating new objects with new calling methods.
Inheritance (Part 5) Odds and ends 1. Static Methods and Inheritance  there is a significant difference between calling a static method and calling a.
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Interfaces and Inner Classes
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Classes, Interfaces and Packages
Access Specifier. Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. When a member.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
Chapter 5: Arrays in Java. The objectives of this chapter are:  1. To discuss the creation and use of Arrays.   2. To continue to use the String class.
Object Oriented Programming Lecture 2: BallWorld.
1 clone() Defined in Object Creates an identical copy –Copies pointers to fields (does not copy fields of fields) –Makes a shallow copy if the object’s.
Java and C# - Some Commonalities Compile into machine-independent, language- independent code which runs in a managed execution environment Garbage Collection.
C#.Net Software Development Version 1.0. Overview Inheritance Member Access Constructors Polymorphism (Name Hiding) Multilevel Hierarchy Virtual and VTable.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Chapter 7 User-Defined Methods.
C Programming Tutorial – Part I
University of Central Florida COP 3330 Object Oriented Programming
Extending Classes.
Java Programming Language
An Introduction to Java – Part I, language basics
The Building Blocks Classes: Java class library, over 1,800 classes:
Presentation transcript:

Java for C++ Programmers A Brief Tutorial

Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions

Classes Everything is contained in a class Simple Example class Foo { private int x; public void setX(int num) { x = num; } public int getX() { return x; }

Classes Fields: member variables –initialized to 0, false, null, or ‘\u000’ Methods: member functions Accessibility –private: only local methods –public: any method –protected: only local and derived classes

Objects All objects are accessed and passed by reference –similar to pointers in C/C++ No explicit control of these “pointers” Warning: use of ==, !=, and = –more on this later

Simple Program Class FirstProgram { public static void main(String [] args) { Foo bar = new Foo(); bar.setX(5); System.out.println(“X is “ + bar.getX()); } compiling: prompt> javac FirstProgram.java –javac determines dependencies –above line create the file FirstProgram.class running: prompt> java FirstProgram

Programming Conventions class naming –capitalize first letter of each word –examples: Foo, NumBooks, ThisIsATest field, method, and object naming –capitalize all words except the first –examples: bar, testFlag, thisIsAnotherTest constants naming –capitalize all letters –examples: PI, MAX_ELEMENTS

Constructors called on object creation (similar to C++) to do some initial work and/or initialization can have multiple constructors constructors are always public and always the same name as the class no such thing as a destructor (java uses garbage collection to clean up memory)

Constructor Example class Example { private boolean flag; public Example() { flag = true; } public Example(boolean flag) { this.flag = flag; } this.___ operator used to access object field otherwise, parameter overrides object field

Arrays similar to C++ in function –consecutive blocks of memory (first index is 0) different from C++ in key ways –creation:int [] grades = new int[25]; –__.length operator: keeps track of array size –out-of-bounds exception: trying to access data outside of array bounds generates an exception

Array Example public void arrayTest() { int [] grades = new int(25); for(int i=0; i<grades.length; i++) array[i] = 0; } access arrays same as in C++ notice no parenthesis after the.length could also make an array of objects (similar to a 2-D array in C++)

Strings standard class in Java comparing strings –__.equals(String st): returns true if equal –__.toCompare(String st): similar to strcmp warning: using ==, !=, and = concatenation: use the + operator string length: use the __.length() method lots more methods for strings

Inheritance lets one class inherit fields and methods from another class use keyword extends to explicitly inherit another classes public and protected fields/methods can only explicitly extend from one class all classes implicitly extend the Object class

Object Class an Object object can refer to any object –similar to void pointer in C/C++ key methods in Object class –__.equals(Object obj) –__.hashCode() –__.clone() above methods inherited by all classes

__.equals(Object obj) Method by default only true if obj is the same as this usually need to override this method warning: ==, !=, = Example class Foo { private Character ch; public Foo(Character ch) { this.ch = ch; } public Character getCh() { return ch; } public boolean equals(Object ch) { return this.ch.charValue() == ((Foo)ch).getCh().charValue(); }

__.equals(Object obj) Method Example (continued) class Tester { public void static main(Strings [] args) { Character c1 = new Character(‘a’); Character c2 = new Character(‘a’); Foo obj1 = new Foo(c1); Foo obj2 = new Foo(c2); if(obj1.equals(obj2)) System.out.println(“Equal”); else System.out.println(“Not Equal”); }

__.hashCode and __.clone Methods __.hashcode hashes object to an integer –default usually returns a unique hash __.clone returns a copy of object –default sets all fields to the same as original can overide either of these functions

Inheritance overriding a method –must have the same signature as original –declaring a method final means future derived classes cannot override the method overloading a method –method has same name but different signature –they are actually different methods

Inheritance Example class Pixel { protected int xPos, yPos; public Pixel(int xPos, int yPos) { this.xPos = xPos; this.yPos = yPos; } public int getXPos() { return xPos; } public int getYPos() { return yPos; }

Inheritance Example (cont.) class ColorPixel extends Pixel { private int red, green, blue; public ColorPixel(int xPos, int yPos, int red, int green, int blue) { super(xPos, yPos); this.red = red; this.green = green; this.blue = blue; } public int getRed() { return red; } public int getGreen() { return green; } public int getBlue() { return blue; }

Inheritance abstract classes and methods –declaring a class abstract must have an abstract method class cannot be directly used to create an object class must be inherited to be used –declaring a method abstract method must be defined in derived class

Abstract Class abstract class Pixel {... public abstract void refresh(); } class ColorPixel extends Pixel {... public void refresh() { do some work } Note: signature of method in derived class must be identical to parent declaration of the method

Interface basically an abstract class where all methods are abstract cannot use an interface to create an object class that uses an interface must implement all of the interfaces methods use the implements keyword a class can implement more than one interface

Interface simple example class Tester implements Foo, Bar {... } Foo and Bar are interfaces Tester must define all methods declared in Foo and Bar

Static Fields and Methods field or methods can be declared static only one copy of static field or method per class (not one per object) static methods can only access static fields and other static methods accessed through class name (usually)

Static Fields and Methods simple example class Product { private static int totalNumber = 0; private int partNumber; public Product() { partNumber = totalNumber; totalNumber++; }... } only one copy of totalNumber

Static Fields and Methods class Product object one object two totalNumber = 2 partNumber = 0partNumber = 1

Exceptions some methods throw exceptions –public void checkIt() throws tooBadException methods that throw exceptions must be called from within try block usually have a catch block that is only executed if an exception is thrown any block of code can be executed in a try block

Exception Example class ExceptTest { public static void main(String [] args) { int [] grades = new int(25); try{ for(int i=0; i<=25; i++) grades[i] = 100; } catch(Exception e) { System.out.println(e); }

Odds and Ends reading data from users –more complicated than simple cin –example public static void main(String [] args) { InputStreamReader input = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(input); String line = in.readLine();... }

Odds and Ends using string tokens –words in a sentence –StringTokenizer class hasMoreTokens() and nextToken() methods default delimitter is white space (could use anything) –example String line = new String(“Hello there all!”); StringTokenizer tok = new StringTokenizer(line); while(tok.hasMoreTokens()) { String tmp = tok.nextToken();... }

Odds and Ends using string tokens (continued) 3 separate strings inside the tokenizer class Hello there all! Hello thereall! call to new StringTokenizer()

Odds and Ends utilizing files in a code library –use the import command –example import java.lang.*; –* indicates to include all files in the library