SMI - Introduction to Java


Published on

SMI - Introduction to Java

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

SMI - Introduction to Java

  1. 1. Samsung University Program
  2. 2. What is Java <ul><li>High Level Language </li></ul><ul><li>Object Oriented programming language </li></ul><ul><li>Platform Independent Language (Portable) </li></ul><ul><li>Robust, Secure </li></ul><ul><li>Multithreaded </li></ul><ul><li>Built in Networking </li></ul>
  3. 3. Object Oriented Language <ul><li>model organized around &quot;objects&quot; and “data” </li></ul><ul><li>Objects have two sections, fields (instance variables) and methods </li></ul><ul><li>Fields tell you what an object is. Methods tell you what an object does. </li></ul><ul><li>These fields and methods are closely tied to the object's real world characteristics and behaviour </li></ul><ul><li>When a program is run objects communicate with each other using methods and variables </li></ul>
  4. 4. Programming Paradigm <ul><li>Programming, at a high level, is the process of solving a problem in an abstract fashion, then writing that solution out in code. </li></ul><ul><li>Object Orientated Programming and Procedure Oriented Programming are two different ways of thinking about and modeling the problem's solution. </li></ul>
  5. 5. Comparing OOP and PPL <ul><li>Object Oriented programming deals with the elemental basic parts or building blocks of the problem </li></ul><ul><li>Procedural programming focuses on the steps (procedures and functions) required to produce the desired outcome. </li></ul><ul><li>In OOL, more emphasis is given on data rather than procedures </li></ul><ul><li>Programs are divided into Objects and the data is encapsulated (Hidden) from the external environment, providing more security to data. Not applicable to PPL. </li></ul>
  6. 6. Comparing OOP and PPL contd.. <ul><li>In OOL, the Objects communicate with each other via Functions. There is no communication in PPL rather its simply a passing values to the Arguments to the Functions and / or procedures. </li></ul><ul><li>OOL concepts includes Inheritance, Encapsulation and Data Abstraction, Polymorphism etc while PPL is simply a traditional way of calling functions and returning values. </li></ul>
  7. 7. Concepts of OOPs <ul><li>Encapsulation - mechanism that binds together code and data in manipulates, and keeps both safe from outside interference and misuse. </li></ul><ul><li>Inheritance - process by which one object acquires the properties of another object </li></ul><ul><li>Polymorphism - one name many forms. &quot;one interface, multiple methods&quot;. </li></ul><ul><li>Abstraction - technique of choosing common features of objects and methods is known as abstracting. It also involves with concealing the details and highlighting only the essential features of a particular object or a concept. </li></ul>
  8. 8. Advantages of OOPs <ul><li>Simpler, easier to read programs </li></ul><ul><li>More efficient reuse of code </li></ul><ul><li>Faster time to market </li></ul><ul><li>More robust, error-free code </li></ul>
  9. 9. “ Write Once Run Anywhere” <ul><li>Programs are first written in plain text files ending with the .java extension. </li></ul><ul><li>programs are compiled into the Java Virtual Machine (JVM) code called bytecode. File with .class extension </li></ul><ul><li>Bytecode is machine-independent and can run on any machine that has JVM </li></ul><ul><li>The byte code is easily interpreted and therefore can be executed on any platform having a JVM </li></ul>
  10. 10. Robust , Secure <ul><li>No memory pointers </li></ul><ul><li>Garbage collection -- no bad addresses </li></ul><ul><li>Bounds checking </li></ul><ul><li>Programs runs inside the virtual machine sandbox. </li></ul><ul><li>Exception Handling </li></ul>
  11. 11. Multithreading <ul><li>program’s capability to perform several tasks simultaneously </li></ul><ul><li>e.g. downloading a video file while playing the video would be considered multithreading </li></ul><ul><li>Multithreading is particularly useful in graphical user interface (GUI) and network programming. </li></ul>
  12. 12. Java Components <ul><li>Java Virtual Machine. </li></ul><ul><li>Java Application Programming Interface (API) </li></ul>
  13. 13. Java Development Kit <ul><li>The Java Development Kit (JDK) is a Sun Microsystems product aimed at Java developers. </li></ul><ul><li>Program development environment for writing Java applications </li></ul><ul><li>It consists of a runtime environment that &quot;sits on top&quot; of the operating system layer as well as the tools and programming that developers need to compile, debug, and run applications written in the Java language. </li></ul>
  14. 14. Installing Java Development Kit <ul><li>SMI -> Knowledge Base -> Installing JDK Article </li></ul><ul><li>JDK Stored on path: c:>Softwares </li></ul>
  15. 15. HANDS On <ul><li>HANDS On </li></ul>
  16. 16. CLASSPATH <ul><li>The CLASSPATH environment variable is used by Java to determine where to look for classes referenced by a program. </li></ul><ul><li>In the CLASSPATH, you do not need to specify the location of normal java packages and classes such as java.util or </li></ul><ul><li>Open the System Properties window (by right-clicking on My Computer and selecting Properties, or through the Control Panel - Start -> Control Panel -> System) </li></ul>
  17. 17. CLASSPATH contd.. <ul><li>On the Advanced tab, click the Environment Variables button. </li></ul><ul><li>On the Environment Variables windows, if a CLASSPATH variable is already defined, then select it and click Edit. If one is not defined, then click the New button. </li></ul><ul><li>On the User Variable window, the variable name should be CLASSPATH. Set the value as appropriate. </li></ul><ul><li>Note that different class file location values should be separated with a semicolon on a Windows machine. </li></ul>
  18. 18. Object <ul><li>Data structures consisting of States (data fields) and behavior (methods) together with their interaction </li></ul><ul><li>E.g. Dogs : State (name, color, breed ..) & Behavior (barking, fetching ..) </li></ul><ul><li>object stores its state in fields (variables) and exposes its behavior through methods (functions) </li></ul><ul><li>Methods operate on an object's state and serve as the primary mechanism for object-to-object communication </li></ul>
  19. 19. Object contd.. <ul><li>class Bicycle { </li></ul><ul><li>/*Fields, Variables */ </li></ul><ul><li>int cadence = 0; /*integer DATA TYPE*/ </li></ul><ul><li>int speed = 0; </li></ul><ul><li>int gear = 1; </li></ul><ul><li>/*Methods*/ </li></ul><ul><li>void changeCadence(int newValue) { cadence = newValue; } </li></ul><ul><li>void changeGear(int newValue) { gear = newValue; } </li></ul><ul><li>void speedUp(int increment) { speed = speed + increment; } </li></ul><ul><li>void applyBrakes(int decrement) { speed = speed - decrement; } </li></ul><ul><li>} </li></ul>
  20. 20. Class <ul><li>blueprint from which individual objects are created. </li></ul><ul><li>this blueprint describes the state and behavior that the objects of the class all share. </li></ul><ul><li>An object of a given class is called an instance of the class. </li></ul><ul><li>Create Bicycle objects </li></ul><ul><li>Bicycle bike1 = new Bicycle(); </li></ul><ul><li>Bicycle bike2 = new Bicycle(); </li></ul><ul><li>Invoke methods on those objects </li></ul><ul><li>bike1.changeCadence(50); </li></ul><ul><li>bike2.changeCadence(20); </li></ul>
  21. 21. Elements of Java <ul><li>Literals - Any number, text, or other information that represents a value. </li></ul><ul><li>Example int abc = 10; private static final int xyz = 25; </li></ul><ul><li>Identifiers - Identifiers are the names of variables, methods, classes, packages and interfaces </li></ul><ul><li>Datatype - Set of data with values having predefined characteristics and operators you can perform on them </li></ul><ul><li>Keywords - Keywords are identifiers that cannot be use by end user as variable name </li></ul><ul><li>Symbols - ; , / etc </li></ul>
  22. 22. DataTypes of Java
  23. 23. Java Keywords <ul><li>abstract, assert, boolean, break, byte, case, catch, char, class, const, continue, default, do, double, else, enum, extends, false, final, finally, float, for, goto, if, implements, import, instanceof, int, interface, long, native, new, null, package, private, protected, public, return, short, static, strictfp, super, switch, synchronized, this, throw, throws, transient, true, try, void, volatile, while </li></ul>
  24. 24. Java Symbols <ul><li>; Semi-colon indicates the end of a statement </li></ul><ul><li>() Parentheses used in several places including: method, casting </li></ul><ul><li>[] square brackets used in array declaration </li></ul><ul><li>{} curly braces used to enclose the code of method </li></ul><ul><li>// Indicates a single line comment </li></ul><ul><li>/*..*/ comments that can span more than one line. </li></ul>
  25. 25. Java Symbols contd.. <ul><li>: colon used in switch statements and in conditional operator. </li></ul><ul><li>&quot; &quot; Double quotes surround a string literal. </li></ul><ul><li>' ' Single quotes surround a character literal. </li></ul><ul><li>+,-,etc Operator symbols. </li></ul><ul><li>? Used with the conditional operator x = boolean ? y : z; </li></ul>
  26. 26. HelloProfessor Program <ul><li>Open any TextEditor and write down the following program </li></ul><ul><li>/* The HelloProfessor class implements an application that displays result to the standard output. */ </li></ul><ul><li>public class HelloProfessor { </li></ul><ul><li>/*visibility [final] [static][synchronize] dataType variable name [ = initialization value ]*/ </li></ul><ul><li>public final static String ProfessorName = &quot;Type your name here&quot;; </li></ul><ul><li>public String SMI = &quot;SMI&quot;; </li></ul><ul><li>public HelloProfessor() { } /*Constructor*/ </li></ul><ul><li>/*visibility [final] [static][synchronize] returnType methodName([parameterList])*/ </li></ul><ul><li>public static void main(String args[]) { </li></ul><ul><li> /*HelloProfessor Object*/ </li></ul><ul><li> HelloProfessor helloProfessor = new HelloProfessor(); </li></ul><ul><li> /*display result on Standard Output*/ </li></ul><ul><li> System.out.println(&quot;Hello &quot;+HelloProfessor.ProfessorName); </li></ul><ul><li> System.out.println(&quot;Welcome to Samsung University Program!!!&quot;); </li></ul><ul><li> System.out.println(&quot;Welcome to &quot;+helloProfessor.SMI); </li></ul><ul><li> } </li></ul><ul><li>} </li></ul><ul><li>Save file as </li></ul>
  27. 27. HelloProfessor Program Contd.. <ul><li>name of class is same as name of file ( .java extension) </li></ul><ul><li>body of class surrounded by { } </li></ul><ul><li>this class has one method called main. All Java applications must have a main method in one of the classes. execution starts here </li></ul><ul><li>body of method within { } </li></ul><ul><li>all other statements end with semicolon ; </li></ul>
  28. 28. Compiling HelloProfessor Program <ul><li>Use compiler called javac which is provided by java. </li></ul><ul><li>Go to the command prompt and type </li></ul><ul><li>drive: > javac </li></ul><ul><li>javac compiler will create a class file called HelloProfessor.class that contains only bytecodes. </li></ul><ul><li>These bytecodes have to be interpreted by a Java Virtual Machine(JVM) that will convert the bytecodes into machine codes. </li></ul>
  29. 29. Running HelloProfessor Program <ul><li>Once we successfully compiled the program, we need to run the program in order to get the output. </li></ul><ul><li>this can be done by the java interpreter called java. In the command line type as shown here. </li></ul><ul><li>Go to the command prompt and type </li></ul><ul><ul><li>drive: > java HelloProfessor </li></ul></ul><ul><li>the output will be displayed as Hello Professor name </li></ul>
  30. 30. Methods <ul><li>information needed to do their job </li></ul><ul><li>methods break down large problems into smaller ones </li></ul><ul><li>your program may call the same method many times </li></ul><ul><li>saves writing and maintaining same code </li></ul><ul><li>methods can take parameters </li></ul><ul><li>methods can return a value. must specify type of value returned </li></ul>
  31. 31. Method Signature <ul><li>visibility [static] returnType methodName(parameterList) </li></ul><ul><li>visibility: </li></ul><ul><li>public : accessible to other objects and classes </li></ul><ul><li>protected : accessible to classes which inherit from this one </li></ul><ul><li>private : accessible only to own class </li></ul><ul><li>default : access only to classes within same package </li></ul><ul><li>static keyword: </li></ul><ul><li>use when method belongs to class as whole not object of the class </li></ul>
  32. 32. Method Signature contd.. <ul><li>return type: </li></ul><ul><li>specifies type of information returned. </li></ul><ul><li>can be a simple data type int, float, double, char, String, boolean or a class </li></ul><ul><li>if nothing returned, use keyword void method name </li></ul><ul><li>parameterList: </li></ul><ul><li> list of datatype , objects etc </li></ul><ul><li>comma seperated list </li></ul>
  33. 33. Variable Signature <ul><li>visibility [final] [static] datatype variableName </li></ul><ul><li>visibility: </li></ul><ul><li>public : accessible to other objects and classes </li></ul><ul><li>protected : accessible to classes which inherit from this one </li></ul><ul><li>private : accessible to own class </li></ul><ul><li>default : access to classes within same package. </li></ul><ul><li>static keyword: </li></ul><ul><li>when method belongs to class as whole and not object </li></ul><ul><li>final keyword: </li></ul><ul><li>constant value that cannot be changed </li></ul>
  34. 34. Application Structure <ul><li>[package packagename ;] </li></ul><ul><li>[import packagename.classname ;] or [import packagename.*; ] </li></ul><ul><li>[visibility] [abstract] [static] [final] class classname [implements interfacename ] [extends superclass ] </li></ul><ul><li>OR </li></ul><ul><li>[visibility] interface interfacename [extends interfacename ] </li></ul><ul><li>{ </li></ul><ul><li> [ [visibility] [static] [final] [datatype varaible = initialization ;] ] </li></ul><ul><li> [constructor] /*method without return type & method name same as classname*/ </li></ul><ul><li>[ [visibility] [static] [final] [returnType] [ methodname ] ( [ parameterList ] ) { } ] </li></ul><ul><li>} </li></ul>
  35. 35. Application Structure contd.. <ul><li>public - indicates that the method can be called by any object </li></ul><ul><li>static - indicates that the method is a class method, which can be called without the requirement to instantiate an object of the class </li></ul><ul><li>void - indicates that the method doesn't return any value </li></ul><ul><li>main(String args[]) - it's the entry point for your application and will subsequently invoke all the other methods required by your program. </li></ul>
  36. 36. Constructor <ul><li>creates an Object of the class i.e. it initialize all instance variables and creates place in memory to hold the Object. </li></ul><ul><li>Constructor name is the same as the class name </li></ul><ul><li>Instead of a return type and a name, just use the class name </li></ul><ul><li>Every class has a constructor to make its objects </li></ul><ul><li>If you don’t define a constructor, a default one will be created. </li></ul><ul><li>Sets all the fields of the new object to default value (if not provided) </li></ul><ul><li>You can supply arguments </li></ul>
  37. 37. Visibilty of variable / methods <ul><li>public: keyword applied to a class, makes it available/visible everywhere. Applied to a method or variable, completely visible. </li></ul><ul><li>private: fields or methods for a class only visible within that class. Private members are not visible within subclasses, and are not inherited. </li></ul><ul><li>protected: members of a class are visible within the class, subclasses and also within all classes that are in the same package as that class. </li></ul>
  38. 38. Package <ul><li>Java’s way of grouping a number of related classes and/or interfaces together into a single unit. </li></ul><ul><li>Programmers also typically use packages to organize classes belonging to the same category or providing similar functionality. </li></ul><ul><li>The package statement must appear as the first statement in a file of Java source code, if it appears e.g. package abc; </li></ul><ul><li>A package is the Java version of a library </li></ul>
  39. 39. Benefits of Package <ul><li>The classes contained in the packages of other programs/applications can be reused. </li></ul><ul><li>Resolves classname conflicts: two classes in two different packages can have the same name. If there is a naming clash, then classes can be accessed with their fully qualified name. </li></ul><ul><li>Classes in packages can be hidden if we don’t want other packages to access them. </li></ul><ul><li>Classes in the same package can access each other's package-access members. </li></ul>
  40. 40. Visibility of Package
  41. 41. Import <ul><li>There are two ways of accessing the classes or class methods stored in packages: </li></ul><ul><li>Using fully qualified class name java.lang.Math.sqrt(x); </li></ul><ul><li>Import package and use class name directly. </li></ul><ul><li>The import directive tells the compiler where to look for the class definitions when it comes upon a class. </li></ul><ul><li>import java.lang.Math and then use Math.sqrt(x); </li></ul>
  42. 42. Import contd.. <ul><li>Selected or all classes in packages can be imported: </li></ul><ul><li>import package.class; or import package.*; </li></ul><ul><li>By default Implicit in all programs: import java.lang.*; </li></ul><ul><li>The general form of importing package is: </li></ul><ul><li>import package1[.package2][…].[classname][.*]; </li></ul><ul><li>Example: </li></ul><ul><ul><li>import myPackage.ClassA; </li></ul></ul><ul><li>or </li></ul><ul><li> import myPackage.secondPackage.*; </li></ul>
  43. 43. Operators & Control Flows <ul><li>Almost exactly like regular ANSI C. </li></ul><ul><li>+, *, -, /, %, ++, --, +=, etc. </li></ul><ul><li>==, !=, >, < , etc. </li></ul><ul><li>if statements, for loops, while loops, do loops, switch statements, etc. </li></ul><ul><li>continue, break, return. </li></ul>
  44. 44. Final classes , methods, variables <ul><li>Final class, why? - increase system security: disables creating a subclass of a class and then substituting for the original one - good object-oriented design: your class should have no subclasses </li></ul><ul><li>Final methods, why? </li></ul><ul><li>- To protect some of your class's methods from being overridden declare them final. </li></ul><ul><li>Final variables, why? </li></ul><ul><li>- Doesn’t allow to change the value of the variable. </li></ul>
  45. 45. Constructor Invocation <ul><li>The constructors are called either explicitly or implicitly from base-class to sub-class down the inheritance hierarchy. </li></ul><ul><li>The compiler forces invocation of base-class constructor as the first thing that happens in the sub-class constructor , this means you cannot catch any exception thrown in the base-class's constructor. </li></ul>
  46. 46. Inheritance <ul><li>All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes </li></ul><ul><li>Inheritance in OOP is analogous to inheritance in humans </li></ul><ul><li>Inheritance and hierarchical organization allow you to capture the idea that one thing may be a refinement or extension of another </li></ul><ul><li>Inheritance allows a software developer to derive a new class from an existing one, for the purpose of reuse, enhancement, adaptation, etc. </li></ul>
  47. 47. Inheritance contd.. <ul><li>The existing class is called the parent class, or superclass, or base class </li></ul><ul><li>The derived class is called the child class or subclass. </li></ul><ul><li>As the name implies, the child inherits characteristics of the parent </li></ul><ul><li>That is, the child class inherits the methods and data defined for the parent class. </li></ul><ul><li>creates a IS-A relationship meaning child is a more specific version of parent. </li></ul>
  48. 48. Class Hierarchy <ul><li>A child class of one parent can be the parent of another child, forming class hierarchies </li></ul><ul><li>At the top of the hierarchy there’s a default class called Object . </li></ul>
  49. 49. Extends <ul><li>In Java, we use the reserved word extends to establish an inheritance relationship. </li></ul><ul><li>Multiple inheritance is not supported in java </li></ul><ul><li>public class Parent { </li></ul><ul><li> /* class contents */ </li></ul><ul><li> int weight; </li></ul><ul><li> public int getWeight() {…} </li></ul><ul><li>} </li></ul><ul><li>public class Child extends Parent { </li></ul><ul><li> /* class contents */ </li></ul><ul><li> public void write() {…} </li></ul><ul><li> public int getWeight() {…} /* override */ </li></ul><ul><li> public int getWeight(int abc) {…} /* overload */ </li></ul><ul><li>} </li></ul>
  50. 50. Overriding <ul><li>If a method in a subclass has the same name and type signature as a method in its superclass, then method in the subclass is said to override the method in superclass. </li></ul><ul><li>The overriding method has the same name, number and type of parameters, and return type as the method it overrides. </li></ul><ul><li>In java, all methods except of constructors can override the methods of their ancestor class. </li></ul><ul><li>If a method is declared with final modifier, it cannot be overridden </li></ul>
  51. 51. Overriding contd.. <ul><li>A subclass must override methods that are declared abstract in the superclass, or the subclass itself must be abstract. </li></ul><ul><li>If a subclass defines a class method with the same signature as a class method in the superclass, the method in the subclass hides the one in the superclass. </li></ul><ul><li>The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the superclass can be made public, but not private, in the subclass. </li></ul>
  52. 52. Overriding vs Shadowing <ul><li>The distinction between shadowing and overriding has important implications. </li></ul><ul><li>public class Animal { </li></ul><ul><li> public static void hide() { System.out.println(&quot;The hide method in Animal.”); } </li></ul><ul><li> public void override() { System.out.println(&quot;The override method in Animal.&quot;); } </li></ul><ul><li>} </li></ul><ul><li>public class Cat extends Animal { </li></ul><ul><li> public static void hide() { System.out.println(&quot;The hide method in Cat.&quot;); } </li></ul><ul><li> public void override() { System.out.println(&quot;The override method in Cat.&quot;); } </li></ul><ul><li> </li></ul><ul><li> public static void main(String[] args) { </li></ul><ul><li> Animal animal = new Cat(); </li></ul><ul><li> animal.hide(); </li></ul><ul><li> animal.override(); </li></ul><ul><li> } </li></ul><ul><li>} </li></ul><ul><li>Output: The hide method in Animal. The override method in Cat. </li></ul>
  53. 53. Overriding access modifiers <ul><li>The access specifier for an overriding method can allow more, but not less, access than the overridden method. </li></ul><ul><li>For example, a protected instance method in the superclass can be made public, but not private, in the subclass. </li></ul><ul><li>You will get a compile-time error if you attempt to change an instance method in the superclass to a class method in the subclass, and vice versa. </li></ul>
  54. 54. Overloading <ul><li>In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. </li></ul><ul><li>When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. </li></ul><ul><li>Method overloading is one of the ways that Java implements polymorphism. </li></ul>
  55. 55. Overloading contd.. <ul><li>class Overloading { </li></ul><ul><li> void test() { System.out.println(&quot;No parameters&quot;); } </li></ul><ul><li> void test(int a, int b) { System.out.println(&quot;a and b: &quot; + a + &quot; &quot; + b); } </li></ul><ul><li> void test(float a) { System.out.println(&quot;Inside test(double) a: &quot; + a); } </li></ul><ul><li>} </li></ul><ul><li>class Overload { </li></ul><ul><li> public static void main(String args[]) { </li></ul><ul><li> Overloading ob = new Overloading(); </li></ul><ul><li> ob.test(); </li></ul><ul><li> ob.test(10, 20); </li></ul><ul><li> ob.test(123.2); </li></ul><ul><li> } </li></ul><ul><li>} </li></ul>
  56. 56. “ this” <ul><li>“ this” is a reference to the current object — the object whose method or constructor is being called. </li></ul><ul><li>You can refer to any member of the current object from within an instance method or a constructor by using this. </li></ul><ul><li>Can be used with variables or methods or constructors. </li></ul>
  57. 57. Using “this” with a Field <ul><li>The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter. </li></ul><ul><li> public class Point { </li></ul><ul><li> public int x = 0; </li></ul><ul><li> public int y = 0; </li></ul><ul><li>/* constructor */ </li></ul><ul><li>public Point(int x, int y) { </li></ul><ul><li> this.x = x; </li></ul><ul><li> this.y = y; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>Each argument to the constructor shadows one of the object's fields - inside the constructor x is a local copy of the constructor's first argument. To refer to the Point field x, the constructor must use this.x. </li></ul>
  58. 58. Using “this” with a Constructor <ul><li>From within a constructor, you can also use ‘this’ to call another constructor in the same class. Also called as explicit constructor invocation. </li></ul><ul><li> public class Rectangle { </li></ul><ul><li>private int x, y, width, height; </li></ul><ul><li>public Rectangle(int width, int height) { </li></ul><ul><li> this(0, 0, width, height); </li></ul><ul><li>} </li></ul><ul><li> public Rectangle(int x, int y, int width, int height) { </li></ul><ul><li> this.x = x; this.y = y; </li></ul><ul><li>this.width = width; this.height = height; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>Compiler determines which constructor to call, based on the number and type of arguments. </li></ul>
  59. 59. “ super” <ul><li>refers to the superclass (base class) </li></ul><ul><li>usage: </li></ul><ul><li>with a variable or method (most common with a method) </li></ul><ul><li>as a function inside a constructor of the subclass </li></ul><ul><li>you can invoke the overridden method through the use of the keyword super </li></ul><ul><li>can also use super to refer to a hidden field (not recommended) </li></ul>
  60. 60. Accessing Superclass Members <ul><li>If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. </li></ul><ul><li>public class Superclass { </li></ul><ul><li> public void printMethod() { </li></ul><ul><li> System.out.println(&quot;Printed in Superclass.&quot;); </li></ul><ul><li> } </li></ul><ul><li>} </li></ul><ul><li>Here is a subclass, called Subclass, that overrides printMethod(): </li></ul><ul><li>public class Subclass extends Superclass { </li></ul><ul><li>public void printMethod() { /*overrides printMethod in Superclass*/ </li></ul><ul><li> super.printMethod(); </li></ul><ul><li> System.out.println(&quot;Printed in Subclass&quot;); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  61. 61. Accessing Superclass Constructor <ul><li>With super(), the super class no-argument constructor is called. </li></ul><ul><li>With super(parameter list), the superclass constructor with a matching parameter list is called. </li></ul><ul><li>class Employee { </li></ul><ul><li> public Employee(String name, double salary) { …… } </li></ul><ul><li>} </li></ul><ul><li>class Manager extends Employee { </li></ul><ul><li>private double bonus; </li></ul><ul><li>public void setBonus(double bb) { …} </li></ul><ul><li>public Manager ( String name, double salary, double bonus ) { </li></ul><ul><li> super(name, salary); </li></ul><ul><li> this.bonus = bonus; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  62. 62. Abstract <ul><li>There are situations in which you will want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method. </li></ul><ul><li>Sometimes you will want to create a superclass that only defines a generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. </li></ul><ul><li>One way this situation can occur is when a superclass is unable to create a meaningful implementation for a method. </li></ul><ul><li>Example consider Superclass figure in which area() cannot be implemented. The definition of area() is simply a placeholder. It will not compute and display the area of any type of object. </li></ul>
  63. 63. Abstract contd.. <ul><li>you want some way to ensure that a subclass does, indeed, override all necessary methods. Java's solution to this problem is the abstract method. </li></ul><ul><li>An abstract class is a class that is declared abstract - it may or may not include abstract methods </li></ul><ul><li>Abstract classes cannot be instantiated, but can be subclassed. </li></ul><ul><li>An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), abstract type name(parameter-list); </li></ul><ul><li>Any class that contains one or more abstract methods must also be declared abstract. </li></ul>
  64. 64. Abstract contd.. <ul><li>When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract. </li></ul><ul><li>Abstract classes can include as much implementation as they see fit. </li></ul><ul><li>Although abstract classes cannot be used to instantiate objects, they can be used to create object references, because Java's approach to run-time polymorphism is implemented through the use of superclass references. </li></ul>
  65. 65. Abstract contd.. <ul><li>/* Using abstract methods and classes.*/ </li></ul><ul><li> abstract class Figure { </li></ul><ul><li> double dim1, dim2; </li></ul><ul><li> Figure(double a, double b) { dim1 = a; dim2 = b; } </li></ul><ul><li>/* area is now an abstract method */ </li></ul><ul><li> abstract double area(); </li></ul><ul><li> } </li></ul><ul><li> class Rectangle extends Figure { </li></ul><ul><li> Rectangle(double a, double b) { </li></ul><ul><li> super(a, b); </li></ul><ul><li> } </li></ul><ul><li> /* override area for rectangle*/ </li></ul><ul><li> double area() { </li></ul><ul><li> System.out.println(&quot;Inside Area for Rectangle.&quot;); </li></ul><ul><li> return dim1 * dim2; </li></ul><ul><li> } </li></ul><ul><li>} </li></ul>
  66. 66. Abstract contd.. <ul><li>class Triangle extends Figure { </li></ul><ul><li> Triangle(double a, double b) { super(a, b); } </li></ul><ul><li> /* override area for right triangle*/ </li></ul><ul><li> double area() { </li></ul><ul><li> System.out.println(&quot;Inside Area for Triangle.&quot;); </li></ul><ul><li> return dim1 * dim2 / 2; </li></ul><ul><li> } </li></ul><ul><li>} </li></ul><ul><li>class AbstractAreas { </li></ul><ul><li> public static void main(String args[]) { </li></ul><ul><li> // Figure f = new Figure(10, 10); /* illegal cannot be instantiated*/ </li></ul><ul><li> Rectangle r = new Rectangle(9, 5); </li></ul><ul><li> Triangle t = new Triangle(10, 8); </li></ul><ul><li> Figure figref; /* this is OK, no object is created */ </li></ul><ul><li> figref = r; </li></ul><ul><li> System.out.println(&quot;Area is &quot; + figref.area()); </li></ul><ul><li> figref = t; </li></ul><ul><li> System.out.println(&quot;Area is &quot; + figref.area()); </li></ul><ul><li> } </li></ul><ul><li>} </li></ul>
  67. 67. Interface <ul><li>In Java an interface is similar to an abstract class in that its members are not implemented. </li></ul><ul><li>Interfaces are declared using the interface keyword, and may only contain method signatures and constant declarations (variable declarations that are declared to be both static and final). </li></ul><ul><li>An interface may never contain method definitions. </li></ul><ul><li>An interface may extend, any number of interfaces. </li></ul><ul><li>As interfaces are implicitly abstract, they cannot be directly instantiated except when instantiated by a class that implements the said interface. </li></ul>
  68. 68. Interface contd.. <ul><li>If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class to successfully compile. </li></ul><ul><li>Interface can only be implemented by classes or extended by other interfaces. </li></ul><ul><li>An interface may not implement an interface </li></ul><ul><li>benefit of using interfaces is that they simulate multiple inheritance. </li></ul>
  69. 69. Interface contd.. <ul><li>Defining an interface is similar to creating a new class: </li></ul><ul><li>public interface OperateCar {  </li></ul><ul><li> /*constant declarations, if any*/ </li></ul><ul><li> int signalTurn(Direction direction, boolean signalOn); </li></ul><ul><li> int getRadarFront(double distanceToCar, double speedOfCar); </li></ul><ul><li> int getRadarRear(double distanceToCar, double speedOfCar); </li></ul><ul><li> ...... </li></ul><ul><li> /*more method signatures*/ </li></ul><ul><li>} </li></ul><ul><li>Note that the method signatures have no braces and are terminated with a semicolon. </li></ul>
  70. 70. Polymorphism <ul><li>Polymorphism is a term that describes a situation where one name may refer to different methods. </li></ul><ul><li>In java there are two type of polymorphism: overloading type and overriding type. </li></ul><ul><li>When you override methods, java determines the proper methods to call at the program’s run time. Overriding occurs when a class method has the same name and signature as a method in parent class. </li></ul><ul><li>Overloading occurs when several methods have same names with different method signature. Overloading is determined at the compile time. </li></ul>
  71. 71. Encapsulation <ul><li>hiding information from unwanted outside access and attaching that information to only methods that need access to it. </li></ul><ul><li>binds data and operations tightly together and separates them from external access that may corrupt them intentionally or unintentionally. </li></ul><ul><li>Encapsulation is achieved by declaring variables, methods, class with access modifiers </li></ul><ul><li>Providing access through the use of public accessor (getter) and mutator (setter) methods. </li></ul>
  72. 72. Data Abstraction <ul><li>Data abstraction and encapsulation are closely tied together. </li></ul><ul><li>simple definition of data abstraction is the development of classes, objects, types in terms of their interfaces and functionality, instead of their implementation details. </li></ul><ul><li>Abstraction is used to manage complexity. Abstraction decompose complex systems into smaller components </li></ul><ul><li>Implementation (Encapsulation) is the next step </li></ul>
  73. 73. Threads <ul><li>Software that can do multiple things simultaneously is known as concurrent software. </li></ul><ul><li>In concurrent programming, there are two basic units of execution: processes and threads. In the Java programming language, concurrent programming is mostly concerned with threads. However, processes are also important. </li></ul><ul><li>A computer system normally has many active processes and threads. </li></ul><ul><li>A thread is an independent path of execution within a program. </li></ul><ul><li>Threads are sometimes called lightweight processes. </li></ul>
  74. 74. Threads contd.. <ul><li>Threads exist within a process — every process has at least one. Threads share the process's resources, including memory and open files. Threads communicate via shared access to data </li></ul><ul><li>JVM allows an application to have multiple threads of execution running concurrently. </li></ul><ul><li>Multiple threads in process execute same program </li></ul><ul><li>A Java program can have many threads, and these threads can run concurrently, either asynchronously or synchronously </li></ul><ul><li>Every thread in Java is created and controlled by the java.lang.Thread class </li></ul>
  75. 75. Threads contd.. <ul><li>Multithreading refers to two or more tasks executing concurrently within a single program. </li></ul><ul><li>Advantages: </li></ul><ul><li>- Threads are lightweight compared to processes </li></ul><ul><li>- Threads share the same address space and therefore can share both data and code </li></ul><ul><li>- Context switching between threads is usually less expensive </li></ul><ul><li>than between processes </li></ul><ul><li>- Cost of thread intercommunication is relatively low that that of </li></ul><ul><li>process intercommunication </li></ul><ul><li>- Threads allow different tasks to be performed concurrently. </li></ul>
  76. 76. Creating Threads <ul><li>Two ways of creating threads: </li></ul><ul><li>- implementing an Runnable interface </li></ul><ul><li>- extending a Thread class. </li></ul>
  77. 77. Runnable Interface <ul><li>Implementing Runnable Interface </li></ul><ul><li>The Runnable Interface Signature </li></ul><ul><li>public interface Runnable { </li></ul><ul><li>void run(); </li></ul><ul><li>} </li></ul><ul><li>implement the Runnable Interface and then instantiate an object of the class. </li></ul><ul><li>override the run() method into your class which is the only method that needs to be implemented. The run() method contains the logic of the thread. </li></ul>
  78. 78. Runnable Interface contd.. <ul><li>class RunnableThread implements Runnable { </li></ul><ul><li>Thread runner; </li></ul><ul><li>public RunnableThread() { } </li></ul><ul><li> </li></ul><ul><li>public RunnableThread(String threadName) { </li></ul><ul><li> runner = new Thread(this); /*(1) Create a new thread. */ </li></ul><ul><li> runner.start(); /*(2) Start the thread. */ </li></ul><ul><li>} </li></ul><ul><li> public void run() { </li></ul><ul><li> /*Display info about this particular thread*/ </li></ul><ul><li> System.out.println(Thread.currentThread()); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  79. 79. Thread Class <ul><li>Extending Thread class </li></ul><ul><li>class XThread extends Thread { </li></ul><ul><li>XThread() { } </li></ul><ul><li>XThread(String threadName) { </li></ul><ul><li>super(threadName); /*Initialize thread. */ </li></ul><ul><li>System.out.println(this); start(); </li></ul><ul><li>} </li></ul><ul><li>public void run() { </li></ul><ul><li>/*Display info about this particular thread */ </li></ul><ul><li>System.out.println(Thread.currentThread().getName()); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  80. 80. Exceptions <ul><li>An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. </li></ul><ul><li>An exception is an object that enables a program to handle unusual/erroneous situations </li></ul><ul><li>A method can throw an exception </li></ul><ul><li>void doubleArray( int[] A) throws Exception { </li></ul><ul><li>… </li></ul><ul><li>if (Index >= A.length) </li></ul><ul><li> throw new Exception( “array too small ” + Index) </li></ul><ul><li>… </li></ul><ul><li>} </li></ul>
  81. 81. Exceptions contd.. <ul><li>Exception is a class, and all Exception-like objects should be subclasses of Exception. </li></ul>
  82. 82. Extending Exception <ul><li>A method can throw several exceptions (each of which is a subclass of the Exception class) </li></ul><ul><li>public void scaleArray( int[] A, int s) throws ArrayRangeException, IllegalArgumentException </li></ul><ul><li>{ </li></ul><ul><li> … </li></ul><ul><li> if (Index >= A.length) </li></ul><ul><li> throw new ArrayRangeException( “array too small ” + Index) </li></ul><ul><li> … </li></ul><ul><li>} </li></ul><ul><li>class ArrayRangeException must be a subclass of (predefined) class Exception, and one of its constructors takes a string argument </li></ul><ul><li>class IllegalArgumentException is predefined </li></ul>
  83. 83. Exception Propagation <ul><li>A (caller) method can deal with an exception thrown by the method it calls in 2 ways: </li></ul><ul><li>caller method can ignore exception handling </li></ul><ul><li>In this case the exception thrown by the called method will be “passed up” and (effectively) thrown by the caller method </li></ul><ul><li>This exception propagation will continue until the main method which was an access point of the java code, which will throw an error to the user (and print its description in the console output) </li></ul>
  84. 84. Exception Propagation contd.. <ul><li>Except if any of the methods along the caller/callee chain explicitly handles this exception. This breaks the chain of exception propagation, and after the exception is handled, the control returns to normal execution. </li></ul>
  85. 85. Try Catch Statement <ul><li>The try/catch statement encloses some code and is used to handle errors and exceptions that might occur in that code. </li></ul><ul><li>try { </li></ul><ul><li> body-code /*code that might throw exception */ </li></ul><ul><li>} catch (exception-classname variable-name) { </li></ul><ul><li> handler-code </li></ul><ul><li>} </li></ul><ul><li>The variable-name specifies a name for a variable that will hold the exception object if the exception occurs. Finally, the handler-code contains the code to execute if the exception occurs </li></ul>
  86. 86. Try Catch Statement contd.. <ul><li>It is possible to specify more than one exception handler in a try/catch statement. When an exception occurs, each handler is checked in order (i.e. top-down) and the handler that first matches is executed. </li></ul><ul><li>try { </li></ul><ul><li>……… </li></ul><ul><li>} catch(<exceptionclass_1> <obj1>) { </li></ul><ul><li>/*statements to handle the exception*/ </li></ul><ul><li>  } catch(<exceptionclass_2> <obj2>) { </li></ul><ul><li>/*statements to handle the exception*/ </li></ul><ul><li>  } </li></ul>
  87. 87. Try Catch Statement contd.. <ul><li>When an exception is thrown, normal execution is suspended. The runtime system proceeds to find a matching catch block that can handle the exception. If no handler is found, then the exception is dealt with by the default exception handler at the top level. </li></ul><ul><li>try { </li></ul><ul><li>int num1 = 10; </li></ul><ul><li>int num2 = 0; </li></ul><ul><li>int[] intarr = {0,1,2,3,4}; </li></ul><ul><li>res = num1 / num2; </li></ul><ul><li> }catch (ArrayIndexOutOfBoundsException e) { </li></ul><ul><li> System.out.println(&quot;Error…. Array is out of Bounds&quot;); </li></ul><ul><li> }catch (ArithmeticException e) { </li></ul><ul><li> System.out.println (&quot;Can't be divided by Zero&quot;); </li></ul><ul><li> } </li></ul>
  88. 88. Finally Statement <ul><li>The finally block always executes when the try block exits. </li></ul><ul><li>This ensures that the finally block is executed even if an unexpected exception occurs. </li></ul><ul><li>allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. </li></ul><ul><li>Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated. </li></ul>
  89. 89. Finally Statement contd.. <ul><li>try{ </li></ul><ul><li>… </li></ul><ul><li>}catch(Exception obj) { </li></ul><ul><li>… </li></ul><ul><li>}finally { </li></ul><ul><li>… </li></ul><ul><li>} </li></ul><ul><li>The runtime system always executes the statements within the finally block regardless of what happens within the try block. So it's the perfect place to perform cleanup </li></ul>
  90. 90. Thankyou <ul><li>THANKYOU </li></ul>