1 / 112

Lecture 4 K268/3 Software Engineering An Introduction to Java Programming

Lecture 4 K268/3 Software Engineering An Introduction to Java Programming. K268 SENG3100 Software Engineering Edina Hatunić–Webster Edina.Hatunic-Webster@comp.dit.ie. Introduction. Key Benefits of Java. Java is “write once, run anywhere” architecture neutral

Download Presentation

Lecture 4 K268/3 Software Engineering An Introduction to Java Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Lecture 4K268/3 Software EngineeringAn Introduction to Java Programming K268 SENG3100 Software Engineering Edina Hatunić–Webster Edina.Hatunic-Webster@comp.dit.ie

  2. Introduction

  3. Key Benefits of Java • Java is “write once, run anywhere” • architecture neutral • portable across different platforms • due to Java Virtual Machine (JVM) • Security features • highly configurable security levels prevent any piece of Java code doing harm to the host system

  4. Key Benefits of Java • Network-centric platform • easy to work with resources across a network and to create network based applications • Object Oriented • an interacting collection of independent software components • dynamic extensible programs

  5. Key Benefits of Java • Internationalisation • uses 16 bit Unicode characters that represents the phonetic and ideographic character sets of the entire world • Performance • although an interpreted language Java programs run almost as fast as native C, C++ programs • Simple and easy to develop • powerful & well designed set of APIs

  6. 1001100101001 … … Interpreted by JVM class myCode { … … … …} Bytecode myCode.class myCode.java JVM Compiled by Java compiler Source Code Application runs

  7. JVM • JVM provides the run time environment for the bytecode (Java Runtime Environment JRE) • executes the bytecode and causes native machine code instructions to execute on the CPU that the JVM is on  each target platform needs an implementation of the JVM

  8. Basic Program Structure • Basic class definition class className { // field declarations … // method declarations … } • Each program needs a main method to tell the program where to start executing

  9. Simple Java Program public class HelloWorld{ // no fields // main method public static void main (String [] args){ System.out.println("Hello World.."); }}

  10. Objects • An object includes state (fields) and behaviour (methods) • A class object is the blueprint for the instance objects • All code must be included in a class • no inline functions like C++

  11. An Example Class public class Student { // member fieldsString name; // constructor public Student(String name) { this.name=name; } // methods void printDetails(){ System.out.println("\nName: “ + name); } }

  12. Instantiation • Class definition creates “class object” at runtime • To instantiate “instance objects” use new operator ClassName myInstance = new ClassName(); where ClassName() is a constructor Note: no need to allocate the memory for the object like in C++

  13. Using a Class in a Program public class myProg { public static void main(String args []){ // instantiate a Student object Student student= new Student("Joe Bloggs"); // invoke printDetails method student.printDetails(); }}

  14. Using the JDK • Create source files for each class in your program • The name of source file should be the same as the name of class public class myCode { …. …. } SourcefFile: myCode.java

  15. Compiling your source code • Compile each class source file into bytecode (class files) • To compile a java source file javac myCode.java • This creates a classfile called myCode.class

  16. To Run Your Program • To start your program running you run the bytecode of the program control class • The program control class has the main method • To run bytecode – pass it to the JVM java classFileName e.g. java myProg note no .class included

  17. Java Syntax • Primitive data types • Operators • Control statements

  18. Primitive Data Types • Identical across all computer platforms • Portable

  19. Primitive Data Types • char (16 bits) a Unicode character • byte (8 bits) • int (32 bits) a signed integer • short (16 bits) a short integer • long (64 bits) a long integer

  20. Primitive Data Types • float (32 bits) a real number • double (64 bits) a large real number • boolean (8 bits) • values are true or false (keywords) • cannot be converted to and from other data typese.g. while (i!=0) not while(i)

  21. Operators • Additive + - • Multiplicative * / % • Equality == != • Assignment operators = += -= *= /= %=

  22. Operators • Relational operators < <= > >= • Increment operators (postfix and prefix) ++ -- • Conditional operator ?: • String concatenation +

  23. Logical Operators • Not ! • Logical AND && • Logical OR || • Boolean logical AND & • Boolean logical inclusive OR | • Boolean logical exclusive OR ^(true if only one operand is true)

  24. Control Statements • Similarto C/C++ syntax: • if statement if (x != n){ …}else if { … }else { … } • for statement for (int i=0; i<max; i++){ … };

  25. Control Statements • while statement while (x==n ){ …}; • do statement do {…} while( x<=y && x!=0);

  26. Control Statements • switch statement switch (n){ case 1: … break; case 2: case 3: … break; default: break;};

  27. General Points to Note • Case sensitive • Use lower case • objects have capitalised first letter

  28. Objects

  29. Objects • Objects occur in everyday life. • Typical objects in an air-traffic control system are planes, radars and slots. • An object is associated with data (state) • Objects can send messages to each other. • One of the first activities in a project that uses Java is identifying objects.

  30. Objects • Objects communicate via messages. • There are a number of reasons why one object will want to communicate : - In order to extract data from another object. For example, a warehouse object may communicate with a bin object in order to find out how many items of a a particular product are stored in an inventory system. - In order to update another object, for example a plane object might be updated by a radar object when it changes position. - In order to update an object and also retrieve some of the state of the object. For example, in a payroll system an employee object might be updated by a sales object when that employee makes a sale which results in his or her commission being updated and the new value of the commission returned.

  31. Objects Objects communicate via messages Plane Radar I have moved my position

  32. Classes • The class is the key idea in an OO language. • Classes can be used to create objects. • Classes define the data that makes up an object. • They also define the messages sent to an object and the processing that occurs.

  33. Class Skeleton Note capitalisation State can follow methods class Example{ definition of state … definition of methods } Brackets match

  34. Class Skeleton • A class has to have a name, in this case the name is Example. We adopt the convention that classes have a capital first letter. • Following the class is the definition of the variables which make up the state of the objects defined by the class. • This is followed by a definition of all the messages that objects defined by the class are associated with. The code that corresponds to each message is known as a method. • The order is immaterial: the definition of the code could follow the definition of the state; in this course we adopt the convention that state precedes code. • In a class the opening curly bracket which delimits the definitions is matched by a closing curly bracket.

  35. An Example of a Class class Example { int x; add(int k){ x+=k; } set(int k){ x = k } } Class with a single piece of data (instance variable) and two chunks of code known as methods

  36. The main Method • This is a method inserted into the only public class in a file. • It carries out execution of a program and acts like a driver program. • It must be placed in the class: it is a method. • It is of the form public static void main. public static void main (String args[]){ }

  37. Constructors • Constructors are special methods which are used to create space for objects. • They have a special syntax. • They are used in conjunction with the new facility. • They can be associated with any number of arguments ranging from zero.

  38. Example of the Use of a Constructor • When the new facility is used – it will allocate the space for the Employee object and ensure that the variable e will contain a pointer to this area. • Example e = new Example(); • Example f = new Example(23);

  39. How it Works • If you declare no constructors then the Java system will initialise all your scalar instance variables to some default, for example an int will be 0.It will also initialise all object instance variables to null • This is poor programming so you need to define all your constructors. • Roughly same syntax as methods.

  40. Examples of Constructors Example(){ x = 0; } Example(int startValue){ x = startValue; } First constructor is equivalent to default Second constructor initialises instance variable x to argument startValue

  41. Example Of Constructors • Here we see two examples of constructors. The first is a simple default constructor which sets an instance variable to zero. The second is a constructor which sets the instance variable to the value of the argument. • A number of constructors in a class. For example, in a class which has two int instance variables you might find a zero-argument constructor which initialises both the variables to zero, a one argument constructor which sets one instance variable to some value and the other to zero and a third constructor which takes two arguments and initialises both the instance variables to the values of the arguments. • You should carefully consider the patterns of access to your objects before deciding on what constructors to offer.

  42. What Happens Example(12); Java system looks for a class Example, then looks for a single argument constructor, if it finds it then it carries out the code defined by the constructor

  43. Java Errors • Wrong number and type of arguments in method call. • Omitting a constructor. • Misspelling or lower case/upper case problems.

  44. The Use of this • The keyword this has two functions in Java. • It is used within constructors to enable maintainable code to be written. • It is used in methods to refer to the current instance variables.

  45. this in Constructors class Example{ int u; Example(int val){ u = val; } Example(){ this(0); } } Use the constructor defined in this class which has a single int argument

  46. this in Methods class Example{ int k; setValue(int k){ this.k = k; } … } Set the instance variable in this class to the value of the argument of the method

  47. public, private etc. • There are a number of visibility modifiers in Java. • You will mainly come across public and private. • public means everything is allowed access. • private means only entities within a class are allowed access.

  48. Compiling Java Classes • A file can contain any number of Java classes. However, only one can be public • If you have a number of public classes then place them in separate files • Good design dictates that instance variables are private and methods are normally public.

  49. Java Errors • Forgetting that one class in a file must be public. • Forgetting to name the source file the same as the class name.

  50. Java Packages

More Related