Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Object-Oriented Programming OBJECT-ORIENTED PROGRAMMING • allows the programmer to more closely model the problem space • classes • objects • methods & attributes (functions & data members) • encapsulation (functions & data combined) • data/information hiding (control over visibility/access) • expression of relationships between classes • inheritance • code reuse/maintenance Java • maintains basic C syntax and operators - That’s where the similarity ends. • strong support of object-oriented programming • interpreted language • allows “executable” code to be transferred over World Wide Web • strong type checking • well-defined primitive data types • large set of existing packages/class libraries • includes graphics and graphical user interface routines • no pointers (that programmers control directly) • automatic garbage collection • exception handling Introduction to Java for C Programmers Page: 4 Copyright 2014 by James J. Polzin All Rights Reserved Printed: 6/30/14 Applications vs. Applets APPLICATIONS VS. APPLETS • Java programs are of two different types - Applications and Applets • Applications are Java programs that are designed to run on the local machine via the Java interpreter. They are the equivalent of an application written in any other programming language • Applets are Java programs that must be run via a web browser such as Netscape Navigator, Sun’s HotJava or Microsoft’s Internet Explorer. Applets are “dependent” on a browser and are launched via an HTML document. Generally, Applets originate from another machine but run on the local machine Compiling: Source code - Bytecode file - “Pseudo” machine instructions file Executing: I) Application II) Applet Introduction to Java for C Programmers Page: 5 Copyright 2014 by James J. Polzin All Rights Reserved Printed: 6/30/14 Identifiers IDENTIFIERS • Java identifiers follow a naming convention similar to C • may consist of letters, digits, underscore or dollar sign • {you should avoid using the dollar sign since Java uses it.} • first character must be a letter, underscore or dollar sign • no length limit KEYWORDS abstract else interface switch assert enum long synchronized boolean extends native this break false new throw byte final null throws case finally package transient catch float private true char for protected try class goto public void const if return volatile continue implements short while default import static do instanceof strictfp double int super Introduction to Java for C Programmers Page: 8 Copyright 2014 by James J. Polzin All Rights Reserved Printed: 6/30/14 Primitive Data Types PRIMITIVE DATA TYPES Type boolean char byte short int long float double • very similar to data types in C • boolean data type added • char type is 16 bits and contains Unicode characters • separate byte data type for byte sized integers • no unsigned integer types Contains true or false Unicode char signed integer signed integer signed integer signed integer IEEE 754 f.p. IEEE 754 f.p. Default false \u0000 0 0 0 0 0.0 0.0 Size 1 bit 16 bits 8 bits 16 bits 32 bits 64 bits 32 bits 64 bits Min N.A. \u0000 -128 -32768 -2147483648 -9x1018 +1.4x10-45 +4.9x10-324 Introduction to Java for C Programmers Max N.A. \uFFFF 127 32767 2147483647 9x1018 +3.4x10+38 +1.8x10+308 Page: 9 Copyright 2014 by James J. Polzin All Rights Reserved Printed: 6/30/14 Program Structure PROGRAM STRUCTURE • Program structure in Java is “similar” to C. However, all the code in a Java file is part of a class definition • The libraries of routines in Java are called packages. Packages can be more easily accessed by using an import statement reminiscent of the C #include Ex: /* FILE: Example2.java */ // Illustrates some control structures import java.io.IOException; public class Example2 { public static void main( String args[ ] ) throws IOException { int x; System.out.print( "Enter a character: " ); x = System.in.read( ); // A very basic input method, it is of // ... very limited use. if (x == 'A') System.out.println( "That was an 'A'." ); else if (x == 'B') System.out.println( "That was a 'B'." ); } } /* OUTPUT: Example2.java Enter a character: A That was an 'A'. Enter a character: B That was a 'B'. Enter a character: C */ Introduction to Java for C Programmers Page: 10 Copyright 2014 by James J. Polzin All Rights Reserved Printed: 6/30/14 Comments COMMENTS • C style comments /* … */ are allowed • commenting to end-of-line using // is allowed • special javadoc comments using /** … */ allow online documentation to be produced by the javadoc program Ex: /* FILE: Example1.java */ // Illustrates primitive data types and commenting /* C-style comments are part of Java and can still span several lines where they are terminated by: */ import java.io.IOException; /** Is a special Java commenting format that indicates to the "javadoc" program that information in this comment is for it. This comment will be associated with the following class definition or method definition. A real javadoc comment in this position would describe class Example1. */ public class Example1 { public static void main( String args[ ] ) throws IOException { int x = 7; double y = 3.5; byte z = 32; char c = 'A'; // Initialization of variables is required. // Primitive types have default initialization values, however these only apply // ... when the data member is within an object. System.out.print( "Some values will be calculated and displayed below.\n" ); System.out.print( "x = " ); System.out.print( x ); System.out.print( "\n" ); System.out.print( "y = " + y + "\n" ); // x = x + y; // Auto-demotion illegal in Java x = (int)(x + y); // Explicit cast required System.out.print( "x = " ); System.out.println( x ); System.out.print( "z = " ); System.out.println( z ); System.out.println( "c = " + c); // Unicode is transparent if you stick to ASCII conventions c = 'Z'; System.out.println( "c = " + c); c = '\101'; System.out.println( "c = " + c); } } cont… Introduction to Java for C Programmers Page: 11 Copyright 2014 by James J. Polzin All Rights Reserved Printed: 6/30/14 Control Structures CONTROL STRUCTURES • Virtually all the standard C control structures are implemented in Java • • • conditionals if if/else switch for while do while loops regulated transfers of control break continue Ex: /* FILE: Example2.java */ // Illustrates some control structures import java.io.IOException; public class Example2 { public static void main( String args[ ] ) throws IOException { int x; System.out.print( "Enter a character: " ); x = System.in.read( ); // A very basic input method, it is of // ... very limited use. if (x == 'A') System.out.println( "That was an 'A'." ); else if (x == 'B') System.out.println( "That was a 'B'." ); } } /* OUTPUT: Example2.java Enter a character: A That was an 'A'. Enter a character: B That was a 'B'. Enter a character: C */ Introduction to Java for C Programmers Page: 13 Copyright 2014 by James J. Polzin All Rights Reserved Printed: 6/30/14 Class – A basic example CLASS – A BASIC EXAMPLE • A new class is essentially a new data type • Anywhere a primitive data type could be used a class can be used • In object-oriented programming a class definition describes the common characteristics and capabilities of some category of objects • Class definitions allow a programmer to encapsulate these characteristics and capabilities into one definition that gives a complete description of the class of objects • The characteristics of the class are modeled with variables and the capabilities are modeled with functions/methods • Since these variables and methods belong to the class, they are referred to as “members” • The . (dot) operator or “member access” operator is used to access class/object members • Note: All objects are accessed via references and new objects are created using new. Ex: /* FILE: AClass.java */ // Class - defines a type of objectthat can carry around data; // in this case - CtypeStruct // // Note: - There are two classes // // - class AClass exercises/tests class CtypeStruct // - class CtypeStruct models a student public class AClass { public static void main( String args[ ] ) { CtypeStruct student; // reference student = new CtypeStruct( ); student.name = "Joe Cool"; student.gpa = 4.00; student.id = 123456; // new "CtypeStruct" type object // Accessing fields/members/attributes System.out.println( "Student name = " + student.name); System.out.println( "Student gpa = " + student.gpa); System.out.println( "Student id = " + student.id); } } class CtypeStruct{ String name; double gpa; long id; } /* OUTPUT: AClass.java Student name = Joe Cool Student gpa = 4.0 Student id = 123456 */ Introduction to Java for C Programmers Page: 17 Copyright 2014 by James J. Polzin All Rights Reserved Printed: 6/30/14 Arrays ARRAYS Ex: /* FILE: StudentTestDrive.java */ // Arrays in Java // // - Arrays provide a "repository" for several items // ... and make working with "sets" of data easier public class StudentTestDrive { public static void main( String args[ ] ) { Student classroom[ ]; classroom = new Student[3]; classroom[0] = new Student( ); classroom[0].name = "Joe Cool"; classroom[0].gpa = 4.00; classroom[0].id = 123456; classroom[0].display( ); classroom[1] = new Student( ); classroom[1].name = "Joe Llama"; classroom[1].gpa = 3.50; classroom[1].id = 123457; classroom[1].display( ); classroom[2] = new Student( ); classroom[2].name = "Joe Camel"; classroom[2].gpa = 3.25; classroom[2].id = 123458; classroom[2].display( ); System.out.println("\nPrinted again with a for loop: "); for(int i = 0; i<3; i++) classroom[i].display( ); // Arrays know their size System.out.println("\nPrinted and-again with a for loop: "); for(int i = 0; i<classroom.length; i++) classroom[i].display( ); } } class Student{ String name; double gpa; long id; public void display( ) { System.out.println( "Student name = " + name); System.out.println( "Student gpa = " + gpa); System.out.println( "Student id = " + id); } } cont… Introduction to Java for C Programmers Page: 24 Copyright 2014 by James J. Polzin All Rights Reserved Printed: 6/30/14 Arrays – More detail ARRAYS – MORE DETAIL • Arrays function as they did in C with some additions and controls • Arrays are implemented as references • Java arrays know their length • Java performs bounds checking on arrays • The storage that an array “refers” to can change • Storage for an array is created using new or indirectly via an initialization list Ex: /* FILE: MultiArray1.java */ // Multi-dimensional arrays public class MultiArray1 { public static void main( String args[ ]) { int x[ ][ ]; x = new int[5][5]; for(int i = 0; i < 5; i++) for(int j = 0; j < 5; j++) x[i][j] = (i+1)*10 + (j+1); for(int i = 0; i < 5; i++){ for(int j = 0; j < 5; j++) System.out.print( "x[" + i + "][" + j +"] = " + x[i][j]+" System.out.println( ); } "); } } /* OUTPUT: MultiArray1.java x[0][0] x[1][0] x[2][0] x[3][0] x[4][0] = = = = = 11 21 31 41 51 x[0][1] x[1][1] x[2][1] x[3][1] x[4][1] = = = = = 12 22 32 42 52 x[0][2] x[1][2] x[2][2] x[3][2] x[4][2] = = = = = 13 23 33 43 53 x[0][3] x[1][3] x[2][3] x[3][3] x[4][3] = = = = = 14 24 34 44 54 x[0][4] x[1][4] x[2][4] x[3][4] x[4][4] = = = = = 15 25 35 45 55 */ Introduction to Java for C Programmers Page: 29 Copyright 2014 by James J. Polzin All Rights Reserved Printed: 6/30/14 Methods / Functions METHODS / FUNCTIONS • Methods in Java are the equivalent of functions in C. Method is the preferred term for objectoriented environments. • Parameters and return types are defined in the same manner as C. • Primitive data-types are pass-by-value, objects are pass-by-reference. In fact, objects are ALWAYS accessed via references, primitive data-types are not. • Java allows methods to be overloaded i.e., you can have more than one method with the same name. • Overloaded methods are distinguished by their parameter lists. Ex: /* FILE: Method1.java */ /* Illustration of functions/methods defined in an application. */ public class Method1{ public static void main(String args[ ]) { int x,i; for(i=0; i<10; i++) { x = my_random(6); System.out.print("x = "); System.out.println(x); } } static int my_random(int range) { return (int)(Math.random( )*range)+1; } } /* OUTPUT: Method1.java x x x x x x x x x x = = = = = = = = = = 6 1 3 6 6 4 1 3 6 4 */ Introduction to Java for C Programmers Page: 36 Copyright 2014 by James J. Polzin All Rights Reserved Printed: 6/30/14 Constructors/Initializers CONSTRUCTORS/INITIALIZERS • A special set of methods called constructors are used to initialize objects of a class • Constructors are named with the same name as the class they belong to and have no return type • Constructors are called when an object is created with new Ex: /* FILE: AClass7.java */ // Default initialization of an object at "construction" time public class AClass7 { public static void main( String args[] ) { Student s; s = new Student( ); // Note: no initialization information s.name = "Joe Cool"; s.gpa = 4.00; s.id = 123456; s.display( ); } } class Student{ String name; double gpa; long id; public void display( ) { System.out.println( "Student name = " + name); System.out.println( "Student gpa = " + gpa); System.out.println( "Student id = " + id); } } /* OUTPUT: AClass7.java Student name = Joe Cool Student gpa = 4.0 Student id = 123456 */ Introduction to Java for C Programmers Page: 40 Copyright 2014 by James J. Polzin All Rights Reserved Printed: 6/30/14 toString( ) method TOSTRING( ) METHOD • Java has a bias toward Strings. It wants to produce a String representation of every type. • The toString( ) method is used by Java for this purpose. Ex: /* FILE: AClass12.java */ // toString( ) method. public class AClass12 { public static void main( String args[] ) { Student s; s = new Student("Cool Joe", 3.95, 654321); // Initializing constructor used s.display( ); System.out.println("Is a " + s.getGrade( ) + " student."); System.out.println(s.toString( )); } } class Student{ String name; double gpa; long id; public Student( ) { } // default constructor public Student(String n, double g, long i) { name = n; gpa = g; id = i; } public char getGrade( ) { char grade; if (gpa grade else if grade else if grade else if grade else grade >= 3.5) = 'A'; (gpa >= 2.5) = 'B'; (gpa >= 1.5) = 'C'; (gpa >= 0.5) = 'D'; = 'F'; return grade; } cont… Introduction to Java for C Programmers Page: 46 Copyright 2014 by James J. Polzin All Rights Reserved Printed: 6/30/14 static Members STATIC MEMBERS • Classes can contain data and methods that are available to the entire class and are not tied to, or specific to, a particular object. • Classes generally describe objects of the class but can also describe/define things that pertain to the entire class. • The static keyword designates a data member/attribute or method as a “class” member or method. Ex: /* FILE: AClass15.java */ // Class information, static attributes // -- data independent of any particular object public class AClass15 { public static void main( String args[] ) { Student s, s2, s3; s = new Student("Joe Cool", 3.95); s2 = new Student("Cool Joe", 3.5); s3 = new Student("Joe Llama", 3.2); System.out.println(s + " is a " + s.getGrade( ) + " student."); System.out.println(s2 + " is a " + s2.getGrade( ) + " student."); System.out.println(s3 + " is a " + s3.getGrade( ) + " student."); } } class Student{ String name; double gpa; long id; static long count; public Student( ) { id = ++count; } // Keeps count of Student objects // ... and generates id numbers. // default constructor public Student(String n, double g) { name = n; gpa = g; id = ++count; } cont… Introduction to Java for C Programmers Page: 52 Copyright 2014 by James J. Polzin All Rights Reserved Printed: 6/30/14 Encapsulation ENCAPSULATION • In this class we will make a distinction between encapsulation and access. • Encapsulation: The gathering together of attributes and methods within a class or object. • Access: The visibility of classes, attributes and methods within a program. Introduction to Java for C Programmers Page: 60 Copyright 2014 by James J. Polzin All Rights Reserved Printed: 6/30/14 Access Specifiers ACCESS SPECIFIERS • The availability of information about a class or object can be controlled using access specifiers. • There are three access specifiers: public, protected, and private. • There are four types of access: public, protected, package, and private. • • • • Public access means the class/data/method is available to all. It is produced by the public keyword. Protected access means the data/method is available only to other classes in the same package and to any classes derived from the class. Protected access is produced by the protected keyword. Package access means the class/data/method is available only to other classes in the same package. Package access is the default availability or visibility which means it is produced implicitly by not specifying any type of access. Private access means the data/method is available only to the class it is defined in. Private access is produced by the private keyword. It is the most restrictive of the access specifiers. Ex: /* FILE: AClass19.java */ // Access specifiers: controlling scope public class AClass19 { public static void main( String args[ ] ) { Student s, s2, s3; System.out.println("Number of students is: " + Student.getCount( )); s = new Student("Joe Cool", 3.95); s2 = new Student("Cool Joe", 3.5); s3 = new Student("Joe Llama", 3.2); s.id = 127; s.name = "Jim Polzin"; // possible, but inadvisable. // possible, but inadvisable. System.out.println(s + " is a " + s.getGrade( ) + " student."); System.out.println(s2 + " is a " + s2.getGrade( ) + " student."); System.out.println(s3 + " is a " + s3.getGrade( ) + " student."); System.out.println("Number of students is: " + Student.getCount( )); } } class Student{ String name; double gpa; long id; static long count; public Student( ) { id = ++count; } // Keeps count of Student objects // ... and generates id numbers. // default constructor public Student(String n, double g) { name = n; gpa = g; id = ++count; } cont… Introduction to Java for C Programmers Page: 61 Copyright 2014 by James J. Polzin All Rights Reserved Printed: 6/30/14 Getter/Setter Methods GETTER/SETTER METHODS • Also called “accessor/mutator” methods. • Each “visible” attribute should be accessible through a get( ) or accessor method. • Each “modifiable” or “writable” attribute should be alterable through a set( ) or mutator method. • This convention allows a layer/interface to be established between “users/consumers” of a class and the actual implementation provided by the “writer/supplier” of the class. This gives the supplier of the class latitude in being able to modify the actual implementation of the class. As long as the interface still exists, consumer code will not be broken/invalidated by a change to the supplier’s class implementation. This known as de-coupling of the two sets of code; the consumer’s code is not bound/coupled to a specific implementation of the supplier’s code. Ex: /* FILE: AClass22.java */ // Private access - only the class has access // The class can allow "reading" an attribute's value // ... through a getter method // The class can allow "changing" an attribute's value // ... through a setter method // The reason is the class controls the access. The // ... user of the class MUST work within the constraints // ... of the class design. public class AClass22 { public static void main( String args[ ] ) { Student s, s2, s3; System.out.println("Number of students is: " + Student.getCount( )); s = new Student("Joe Cool", 3.95); s2 = new Student("Cool Joe", 3.5); s3 = new Student("Joe Llama", 3.2); System.out.println(s.getName( ) + " has id: " + s.getId( ) + "\n"); // attribute accessible thru get/set methods System.out.println(s + " is a " + s.getGrade( ) + " student."); System.out.println(s2 + " is a " + s2.getGrade( ) + " student."); System.out.println(s3 + " is a " + s3.getGrade( ) + " student."); System.out.println("Number of students is: " + Student.getCount( )); System.out.println( ); System.out.print("Name change: " + s3.getName( ) + " to "); System.out.println(s3.setName("Joe Camel")); } } cont… Introduction to Java for C Programmers Page: 67 Copyright 2014 by James J. Polzin All Rights Reserved Printed: 6/30/14 this Reference THIS REFERENCE • Access to the invoking object in an instance method is provided automatically by Java. • Access is provided thru a reference named this. • The this reference is implicitly used within all instance methods. • The this reference can be used explicitly to confirm its existence and is also used to identify the invoking object. Ex: /* FILE: This.java */ // The this reference: used explicitly public class This { public static void main( String args[ ] ) { Student s, s2, s3; System.out.println("Number of students is: " + Student.getCount( )); s = new Student("Joe Cool", 3.95); s2 = new Student("Cool Joe", 3.5); s3 = new Student("Joe Llama", 3.2); System.out.println(s + " is a " + s.getGrade( ) + " student."); System.out.println(s2 + " is a " + s2.getGrade( ) + " student."); System.out.println(s3 + " is a " + s3.getGrade( ) + " student."); System.out.println("Number of students is: " + Student.getCount( )); } } class Student{ private String name; private double gpa; private long id; private static long count; // Keeps count of Student objects // ... and generates id numbers. public Student( ) // default constructor { this.id = ++count; } public Student(String name, double gpa) { this.name = name; this.gpa = gpa; this.id = ++count; } static public long getCount( ) { return count; } public String getName( ) { return name; } cont… Introduction to Java for C Programmers Page: 72 Copyright 2014 by James J. Polzin All Rights Reserved Printed: 6/30/14 this( ) constructor call THIS( ) CONSTRUCTOR CALL • Another constructor in a class can be called within a constructor by using the this( ) notation in the first line of the constructor. Ex: /* FILE: StudentThisTestDrive.java */ // Access specifiers: controlling scope // Private - only the class has access // this( ) constructor call notation public class StudentThisTestDrive { public static void main( String args[ ] ) { StudentThis s, s2, s3; System.out.println("Number of students is: " + StudentThis.getCount( )); s = new StudentThis("Joe Cool", 3.95); s2 = new StudentThis("Cool Joe", 3.5); s3 = new StudentThis( ); System.out.println(s + " is a " + s.getGrade( ) + " student."); System.out.println(s2 + " is a " + s2.getGrade( ) + " student."); System.out.println(s3 + " is a " + s3.getGrade( ) + " student."); System.out.println("Number of students is: " + StudentThis.getCount( )); } } /* OUTPUT: StudentThisTestDrive.java Number of students is: 0 Joe Cool, 3.95, 1 is a A student. Cool Joe, 3.5, 2 is a A student. , 0.0, 3 is a F student. Number of students is: 3 */ /* FILE: StudentThis.java */ // Class StudentThis // ... one constructor calling another class StudentThis{ private String name; private double gpa; private long id; private static long count; public StudentThis( ) { this("", 0.0); } // Keeps count of Student objects // ... and generates id numbers. // default constructor public StudentThis(String n, double g) { name = n; gpa = g; id = ++count; } cont… Introduction to Java for C Programmers Page: 74 Copyright 2014 by James J. Polzin All Rights Reserved Printed: 6/30/14 Initialization assistance INITIALIZATION ASSISTANCE • Java supports several additional features besides the this( ) constructor notation to assist in initializing instance and class fields. • For both instance and class fields: • Initial values can be provided as part of the field definitions • Initial values can be computed and supplied in an initialization block • A class initialization block executes when a class is first loaded • An instance initialization block executes before each constructor call Ex: /* FILE: StudentInitTestDrive.java */ // Other initialization assistance // ... see the StudentInit class public class StudentInitTestDrive { public static void main( String args[ ] ) { StudentInit s, s2, s3; System.out.println("Number of students is: " + StudentInit.getCount( )); s = new StudentInit("Joe Cool", 3.95); s2 = new StudentInit("Cool Joe", 3.5); s3 = new StudentInit( ); System.out.println(s + " is a " + s.getGrade( ) + " student."); System.out.println(s2 + " is a " + s2.getGrade( ) + " student."); System.out.println(s3 + " is a " + s3.getGrade( ) + " student."); System.out.println("Number of students is: " + StudentInit.getCount( )); } } /* OUTPUT: StudentInitTestDrive.java Number of students is: 2000 Joe Cool, 3.95, 2001 is a A student. Cool Joe, 3.5, 2002 is a A student. <no name>, 0.1, 2003 is a F student. Number of students is: 2003 */ cont… Introduction to Java for C Programmers Page: 76 Copyright 2014 by James J. Polzin All Rights Reserved Printed: 6/30/14