KEMBAR78
Java introduction | PPTX
Java Introduction

Prepared by: Ragab Mustafa
Agenda
•   Overview of Programming Languages.
•   What’s and why Java.
•   What’s Eclipse .
•   Writing first program in Java.
•   Basics of java programming Language.
•   Variables, Operators and Types.
•   Methods, Conditionals and Loops.
Agenda cont.
•   Classes, Arrays and objects.
•   Solving a problems in Java.
•   Object-oriented Programming(OOP).
•   Inheritance.
Overview of Programming Languages.

• There are three types of programming
  languages:
 Machine Languages that encoded in 1’s and 0’s,
  that’s hard to write program in these languages.
 Low Level Languages(e.g. Assembly)it’s close to
  the machine code but not the same also it’s easer
  to write and read(understand).
 High Level Languages (e.g. C,C++,Java and
  C#)these      Languages needs a compiler to
  translate the program into machine code.
What’s Java
• Java is an OOP language developed at Sun
  Microsystems Labs by James Gosling at 1991.
• The first version called “OAK” but at 1995
  “Netscape” announced that Java would be
  incorporated into Netscape Navigator.
• Sun formally announced Java at a major
  conference in May 1995.
• it is also a good not only in “object-oriented
  programming “but also in “general programming
  language”.
Why Java
• Java has some advantages make it differ
  from the other languages as:
o   That it is platform independent(mean work well in the internet). It
    achieves this by using something called the ‘Java Virtual Machine’
    (JVM).




o   It’s a free source language.
Why Java cont.
• Also it’s
1. Simple Architecture       neutral .
2. Object oriented        Portable .
3. Distributed High     performance .
4. Multithreaded       Robust .
5. Dynamic        Secure.
What’s Eclipse
• Eclipse is a portable IDE for java it’s easy and
  powerful.
• There are more than one IDE for java as
  NetBeans, JBuilder and JDeveloper.
Prepare your PC and yourself!
• First you must download JDK from sun or go
  to here.
• Then run the IDE that you will treat with it
  here we will work by Eclipse.
• To download Eclipse IDE go to here or go to
  the home page of Eclipse .
• Just you download the IDE (hint: Eclipse is portable not installed)
  run it that will Explained by video.
The first program in java
• Write the program:
 public class FirstProgram
    {
 public static void main (String[] args)
    {
             System.out.print("Hello, 2 + 3 = ");
             System.out.println(5);
             System.out.println("Good Bye");
    }
 }
Basics of Java
• Program Structure
  class CLASSNAME {
  public static void main(String[] args)
      {
           STATEMENTS
      }
  }
Variables
• Named location that stores a value
• Form:
                 TYPE NAME;
• Example:
                 String fName;
  class Hello {
  public static void main(String[] arguments)
        {
        String fName = “ragab”;
        System.out.println(fName);
        fName = "Something else";
        System.out.println(fName);
        }
  }
Types
• Limits a variable to kinds of values
  String: plain text (“hello”)
  double: Floating-point, “real” valued
  number(3.14, -7.0)
   int: integer (5, -18)
     String fName = “hello”;
     double Pi = 3.14;
Types
• Order of Operations :Precedence like math, left
  to right.
  Right hand side of = evaluated first.
        double x= 20
        double x =3 / 2+ 1; // x= 2.0

• Conversion by casting
        Int a = 2; // a = 2
        double a = (double)2; // a = 2.0
        double a = 2/3; // a = 0.0
        double a = (double)2/3; // a = 0.6666…
        int a = (int)18.7; // a=18
Types
• Conversion by method:
  o Int to String:
     String five = Integer.toString(5);
     String five = “” + 5; // five = “5”
  o String to int:
     Int a=Integer.parseInt(“18”);
• Mathematical Functions:
  o Math.sin(x)
  o Math.cos(Math.PI / 2)
  o Math.log(Math.log(x + y))
Operators
•   Symbols that perform simple computations
•   Assignment: =
•   Addition: +
•   Subtraction: -
•   Multiplication: *
•   Division: /
Example
    class Math {
    public static void main(String[] arguments)
    {
    int score;
    score = 1 + 2 * 3;
    System.out.println(score);
    double copy = score;
    copy = copy / 2;
    System.out.println(copy);
    score = (int) copy;
    System.out.println(score);
    }
}
Methods
• Adding Methods
  public static void NAME() { STATEMENTS }
• To call a method:
  NAME();
• Parameters
  public static void NAME(TYPE NAME) { STATEMENTS }
• To call:
  NAME(EXPRESSION);
Methods
• Example:
  class Square {
    Public static void printSquare(int x){
    System.out.println(x*x);}
  public static void main(String[] arguments){
    int value = 2;
    printSquare(value);
    printSquare(3);
    printSquare(value*22);
     }
  }
Methods
• Multiple Parameters
     *…+ NAME(TYPE NAME, TYPE NAME) {STATEMENTS }
     NAME(arg1, arg2);
• Return Values
     public static TYPE NAME() {
     STATEMENTS
     return EXPRESSION;
      }
  void means “no type”
Conditionals
• if statement
      if (COMPARISON) {STATEMENTS }
• Example:
      class If {
         public static void test((int x)) {
         if (x > 5){
         System.out.println((x + " is > 5");
                  }
         }
      public static void main(String[] arguments){
          test(6);
          test(5);
         test(4);
         }
      }
Conditionals
• Comparison operators
  x > y: x is greater than y
  x< y: x is less than y
  x >= y: x is greater than or equal to y
  x <= y: x is less than or equal to y
  x == y: x equals y (assignment: =)
Conditionals
• else
         if (COMPARISON) {STATEMENTS
         } else {
         STATEMENTS
         }
• else if
         if (COMPARISON) {STATEMENTS
         } else if (COMPARISON) { STATEMENTS
         } else if (COMPARISON) { STATEMENTS
         }
         else {
         STATEMENTS
         }
Conditionals
• Example
   public static void test(int x){
   if (x > 5){
   System.out.println(x + " is > 5");}
    else if (x == 5){
   System.out.println(x + " equals 5");}
   else {
   System.out.println(x +”is < 5"); -
    }
   public static void main(String[] arguments){
    test(6);
   test(5);
    test(4);
   }
Loops
  static void main (String[] arguments) {
  System.out.println(“This is line 1”);
  System.out.println(“This is line 2”);
  System.out.println(“This is line 3”);
  }

• What if you want to do it for 200 lines?
• Loop operators allow to loop through a block
  of code.
• There are several loop operators in Java.
Loops
• The while operator:
     while (condition) {statement}
• Example:
     int i = 0;
     while (i < 3) {
     System.out.println(“This is line “ + i);
     i = i+1;}
• Count carefully
• Make sure that your loop has a chance to finish.
Loops
• The for operator:
      for (initialization;condition;update){statement}
• Example:
          int i;
          for (i = 0; i < 3; i=i++) {
          System.out.println (“This is line “ + i);}
• Embedded loops:
      for (int i = 0; i < 3; i++) {
      for (int j = 2; j < 4; j++){
      System.out.println (i + “ “ + j);
      } }
• Scope of the variable defined in the initialization:
  respective for block
Loops
• Branching Statements :
• break terminates a for or while loop
       for (int i=0; i<100; i++) {if(i ==
       terminationValue)
       break;
       else {...}
       }
• continue skips the current iteration of a for or while loop
  and proceeds directly to the next iteration
       for (int i=0; i<100; i++) {
       if(i == skipValue)
       continue;
       else {...}
       }
Arrays
• An array is an indexed list of values.
• You can make an array of int, of double, of
  String,etc.All elements of an array must have
  the same type.
   0    1   2   3              n-1



• This array contain n elements.
Arrays
• An array is noted using [] and is declared in the
  usual way:
      int values[]; // empty array
      int[] values; // equivalent declaration
• To create an array of a given size, use the
  operator new :
      int values[] = new int[5];
• or you may use a variable to specify the size:
      int size = 12;
      int values[] = new int[size];
Arrays
• Array Initialization:
• Curly braces can be used to initialize an array in
  the array declaration statement (and only there).
         int values[] = { 12, 24, -23, 47 };

• To access the elements of an array, use the []
  operator: values[index]
• Example:
         int values[] = { 12, 24, -23, 47 };
         values[3] = 18; // write
         int x = values[1] + 3; // read
Arrays
•   Each array has a length variable built-in that contains the length of the array.
                int values[] = new int[12];
                int size = values.length; // 12
•   Looping through an array
•   Example :
           int values[] = new int[5];
           for (int i=0; i<values.length; i++) {
           values[i] = i;
           int y = values[i] *values[i];
           System.out.println(y);
           }
•   Another one:
     double values[] = new double[25];
     int j=0;
     while (j<values.length) {...
     j++;
     }
Objects
• Objects are a collection of related data and
  methods.
• Example:
• Strings A string is a collection of characters
  (letters) and has a set of methods built in.
      String nextTrip = “Mexico”;
        int size = nextTrip.length(); // 6
Objects
• To create a new object, use the new operator.
  If you do not use new, you are making a
  reference to an object (i.e. a pointer to the
  same object).
        Point p;
        p.x = 23;
        p.y = -12;
        public static Point middlePoint (Point p1, Point p2) {
        Point q = new Point ((p1.x+p2.x)/2, (p1.y+p2.y)/2);
        return q; }
Classes
• A class is a prototype to design objects.
• It is a set of variables and methods that
  encapsulates the properties of the class of
  objects.
• In Java, you can (will) create several classes in
  project.
• A class constructor is called each time an
  object of the class is instantiated (created).
Packages
• A package is a set of classes that relate to a
  same purpose.
• Example: math, graphics, input/output...
• In order to use a package, you have to import
  it.                   package


    class               class              class



            object
Object Oriented Programming
• Objects are a collection of related data and
  methods.
• To create a new object, use the new operator.
  If you do not use new, you are making a
  reference to an object (i.e a pointer to the
  same object).
Objects and references
Point p1 = new Point (12,34);
Point p2 = p1;
System.out.println(“x = “ + p2.x); // 12
p1.x = 24;
System.out.println(“x = “ + p2.x); // 24!
The null object
• null simply represents no object. It is
  convenient
• as a return value to mean that a method failed
  for example. It may also be used to “remove”
  an element from an array.
  String values[] = { “ragab”, “ahmed”, “zidan” };
  values[1] = null;
Object methods v.s. class methods
     class Bicycle {
     static int gear, speed;
     public static void speedUp (Bicycle b) {
     b.speed += 10;}
     public static void main (String[] arguments) {
     Bicycle bike1 = new Bicycle();
     speedUp (bike1); }}

• static means that the variable is going to be same
  for all objects of the class.
• Class methods are declared static.
• static = the same for all objects
• nonstatic = different for each object
Abstraction
• Objects are tools for abstraction.
• Abstraction is a fundamental concept in
  computer science.
• In Java, objects are instances of a class.
• A class contains variables and methods that
  capture the essence of the object.
• An object is instantiated using new
Why is abstraction important?
• Modularity (allows to subdivide a big problem
  into smaller sub-problems)
• Powerful representation of real-world
  problems
Inheritance
• In the world, people inherit characteristics
  from their parents.
• In computer science, objects inherit variables
  and methods from their parents.
• When you define a class in Java, you may
  define it as a subclass of another class (its
  parent).
Why inheritance and it’s rules?
• Avoid duplicate code
• Improve modularity
            Inheritance rules
• The subclass inherits all variables and methods
• Use the extends keyword to indicate that one
  class inherits from another
• Use the super keyword in the subclass
  constructor to call the parent constructor
Modularity
Example
      public class Vehicle {
      public int nWheels; // number of wheels
      public Vehicle (int n)
      {nWheels = n;}
      int getNWheels ()
       {return nWheels;}}
• ----------------------------------------
      public class Car extends Vehicle {
      public Car (int n)
       {super (n);}
      public void openWindow() {}
      }
Example
      public class Bicycle extends Vehicle {
      public Bicycle (int n)
       {super (n);}
      public void freeStyle() {}
      }
• -------------------------------------
   public class World {
   public static void main (String[] args) {
   Bicycle bike = new Bike (2);
   Car car = new Car (4);
   System.out.println (“Car has “ +car.getNWheels() + “ wheels”);
   System.out.println (“Bike has “ +bike.getNWheels() + “ wheels”);--
OOP: Scope & Visibility
• Scope:
  – A variable cannot be used outside of
    the curly braces (“,...-”) in which it is declared.
  – E.g., Class-level variables (fields) are usable
    everywhere in the class; loop variables are only
    usable in the scope of the loop
OOP: Scope & Visibility
• Visibility:
  – public fields, methods, & constructors can be “seen”
    or used directly by all classes & subclasses
  – protected fields, methods, & constructors can only
    be seen or used from within their class or subclasses
  – private fields, methods, & constructors can only be
    seen or used from within their exact class (in general,
    most or all of a class’s fields should be private)
  – Fields, methods, and constructors with unspecified
    (“default” or “package”) visibility can be seen by
    some classes – more on this later
OOP: Getter & Setter Methods
•   Another way to access or modify fields
•   Good programming practice
•   Widely-used convention in Java
•   Also called accessors and mutators
•   Don’t come for free, but very useful when
    dealing with private or protected fields
OOP: Ecapsulation
• The Principle of Encapsulation
• Allows one to access and change the internals
  of a class, without having “direct access”
• Visibility, Accessors, & Mutators are vital tools
  for this OOP principle
OOP: this
• A way for an instance of class to refer to itself
   – E.g.: say Engineer has a field called trafficHours and a
     setter method with this signature:
   – public void setTrafficHours(int trafficHours);
   – How to resolve scope?
   – Solution: use this.trafficHours = trafficHours;
   – this does not work inside static methods

• Good programming practice
• Standard Java convention
• Does come for free, has many uses
Inheritance & Abstraction

• A class can extend another (single) class
• Subclasses inherit methods and variables from
  their parents
• This allows us to use objects to form an
  hierarchy of representations
• Classifications of objects and relationships
  between them can now be modeled!
Inheritance & Abstraction:The Object
               class
• Every class implicitly extends Object
• So, in Java, every object is an Object…
• “Class Object is the root of the class hierarchy.
  Every class has Object as a superclass. All
  objects, including arrays, implement the
  methods of this class.” – from the Java API
• Core and backbone of OOP in Java
• Methods of note are equals(Object) and
  toString() – more on these later
Inheritance & Abstraction:Overriding
           & Overloading

• What if we want a subclass’s inherited method
  to do something different than that of its
  parent? – Override it!
• What if we want multiple constructors for a
  class, or methods with the same name but
  different arguments? – Overload them!
Inheritance & Abstraction:Overriding
           & Overloading
• Overriding: re-defining an inherited method
• E.g., Say every Manager gets a weekly bonus
  of amount weeklyBonus (which would be
  defined somewhere in the class)
• To reflect this, we can override the
  weeklyPay() method simply by explicitly
  defining it again in Manager, with the desired
  changes
Inheritance & Abstraction:Overriding
           & Overloading

• Overloading: method or constructor with
  same name and type as another, but with a
  different signature (i.e., takes different
  number, ordering, or types of arguments)
• Cannot have methods with same name and
  arguments and different return type
Method Overriding
• Method overriding occurs when a subclass
  implements a method that is already implemented in a
  superclass. The method name must be the same, and
  the parameter and return types of the subclass's
  implementation must be subtypes of the superclass's
  implementation. You cannot allow less access than the
  access level of the superclass's method.
     eg,
     class Timer {
     public Date getDate(Country c) { ... } }
     class USATimer {
     public Date getDate(USA usa) { ... } }
Method Overloading

• Method overloading is when two methods
  share the same name but have a different
  number or type of parameters.
    eg,
    public void print(String str) { ...
    }
    public void print(Date date) { ...
    }
References
• Java how to program, book.
• Essential Java for scientists and Engineering,
  book.
• MIT Lectures.
• Tutorial from sun.
Java introduction

Java introduction

  • 1.
  • 2.
    Agenda • Overview of Programming Languages. • What’s and why Java. • What’s Eclipse . • Writing first program in Java. • Basics of java programming Language. • Variables, Operators and Types. • Methods, Conditionals and Loops.
  • 3.
    Agenda cont. • Classes, Arrays and objects. • Solving a problems in Java. • Object-oriented Programming(OOP). • Inheritance.
  • 4.
    Overview of ProgrammingLanguages. • There are three types of programming languages:  Machine Languages that encoded in 1’s and 0’s, that’s hard to write program in these languages.  Low Level Languages(e.g. Assembly)it’s close to the machine code but not the same also it’s easer to write and read(understand).  High Level Languages (e.g. C,C++,Java and C#)these Languages needs a compiler to translate the program into machine code.
  • 5.
    What’s Java • Javais an OOP language developed at Sun Microsystems Labs by James Gosling at 1991. • The first version called “OAK” but at 1995 “Netscape” announced that Java would be incorporated into Netscape Navigator. • Sun formally announced Java at a major conference in May 1995. • it is also a good not only in “object-oriented programming “but also in “general programming language”.
  • 6.
    Why Java • Javahas some advantages make it differ from the other languages as: o That it is platform independent(mean work well in the internet). It achieves this by using something called the ‘Java Virtual Machine’ (JVM). o It’s a free source language.
  • 7.
    Why Java cont. •Also it’s 1. Simple Architecture neutral . 2. Object oriented Portable . 3. Distributed High performance . 4. Multithreaded Robust . 5. Dynamic Secure.
  • 8.
    What’s Eclipse • Eclipseis a portable IDE for java it’s easy and powerful. • There are more than one IDE for java as NetBeans, JBuilder and JDeveloper.
  • 9.
    Prepare your PCand yourself! • First you must download JDK from sun or go to here. • Then run the IDE that you will treat with it here we will work by Eclipse. • To download Eclipse IDE go to here or go to the home page of Eclipse . • Just you download the IDE (hint: Eclipse is portable not installed) run it that will Explained by video.
  • 10.
    The first programin java • Write the program: public class FirstProgram { public static void main (String[] args) { System.out.print("Hello, 2 + 3 = "); System.out.println(5); System.out.println("Good Bye"); } }
  • 11.
    Basics of Java •Program Structure class CLASSNAME { public static void main(String[] args) { STATEMENTS } }
  • 12.
    Variables • Named locationthat stores a value • Form: TYPE NAME; • Example: String fName; class Hello { public static void main(String[] arguments) { String fName = “ragab”; System.out.println(fName); fName = "Something else"; System.out.println(fName); } }
  • 13.
    Types • Limits avariable to kinds of values String: plain text (“hello”) double: Floating-point, “real” valued number(3.14, -7.0) int: integer (5, -18) String fName = “hello”; double Pi = 3.14;
  • 14.
    Types • Order ofOperations :Precedence like math, left to right. Right hand side of = evaluated first. double x= 20 double x =3 / 2+ 1; // x= 2.0 • Conversion by casting Int a = 2; // a = 2 double a = (double)2; // a = 2.0 double a = 2/3; // a = 0.0 double a = (double)2/3; // a = 0.6666… int a = (int)18.7; // a=18
  • 15.
    Types • Conversion bymethod: o Int to String: String five = Integer.toString(5); String five = “” + 5; // five = “5” o String to int: Int a=Integer.parseInt(“18”); • Mathematical Functions: o Math.sin(x) o Math.cos(Math.PI / 2) o Math.log(Math.log(x + y))
  • 16.
    Operators • Symbols that perform simple computations • Assignment: = • Addition: + • Subtraction: - • Multiplication: * • Division: /
  • 17.
    Example class Math { public static void main(String[] arguments) { int score; score = 1 + 2 * 3; System.out.println(score); double copy = score; copy = copy / 2; System.out.println(copy); score = (int) copy; System.out.println(score); } }
  • 18.
    Methods • Adding Methods public static void NAME() { STATEMENTS } • To call a method: NAME(); • Parameters public static void NAME(TYPE NAME) { STATEMENTS } • To call: NAME(EXPRESSION);
  • 19.
    Methods • Example: class Square { Public static void printSquare(int x){ System.out.println(x*x);} public static void main(String[] arguments){ int value = 2; printSquare(value); printSquare(3); printSquare(value*22); } }
  • 20.
    Methods • Multiple Parameters *…+ NAME(TYPE NAME, TYPE NAME) {STATEMENTS } NAME(arg1, arg2); • Return Values public static TYPE NAME() { STATEMENTS return EXPRESSION; } void means “no type”
  • 21.
    Conditionals • if statement if (COMPARISON) {STATEMENTS } • Example: class If { public static void test((int x)) { if (x > 5){ System.out.println((x + " is > 5"); } } public static void main(String[] arguments){ test(6); test(5); test(4); } }
  • 22.
    Conditionals • Comparison operators x > y: x is greater than y x< y: x is less than y x >= y: x is greater than or equal to y x <= y: x is less than or equal to y x == y: x equals y (assignment: =)
  • 23.
    Conditionals • else if (COMPARISON) {STATEMENTS } else { STATEMENTS } • else if if (COMPARISON) {STATEMENTS } else if (COMPARISON) { STATEMENTS } else if (COMPARISON) { STATEMENTS } else { STATEMENTS }
  • 24.
    Conditionals • Example public static void test(int x){ if (x > 5){ System.out.println(x + " is > 5");} else if (x == 5){ System.out.println(x + " equals 5");} else { System.out.println(x +”is < 5"); - } public static void main(String[] arguments){ test(6); test(5); test(4); }
  • 25.
    Loops staticvoid main (String[] arguments) { System.out.println(“This is line 1”); System.out.println(“This is line 2”); System.out.println(“This is line 3”); } • What if you want to do it for 200 lines? • Loop operators allow to loop through a block of code. • There are several loop operators in Java.
  • 26.
    Loops • The whileoperator: while (condition) {statement} • Example: int i = 0; while (i < 3) { System.out.println(“This is line “ + i); i = i+1;} • Count carefully • Make sure that your loop has a chance to finish.
  • 27.
    Loops • The foroperator: for (initialization;condition;update){statement} • Example: int i; for (i = 0; i < 3; i=i++) { System.out.println (“This is line “ + i);} • Embedded loops: for (int i = 0; i < 3; i++) { for (int j = 2; j < 4; j++){ System.out.println (i + “ “ + j); } } • Scope of the variable defined in the initialization: respective for block
  • 28.
    Loops • Branching Statements: • break terminates a for or while loop for (int i=0; i<100; i++) {if(i == terminationValue) break; else {...} } • continue skips the current iteration of a for or while loop and proceeds directly to the next iteration for (int i=0; i<100; i++) { if(i == skipValue) continue; else {...} }
  • 29.
    Arrays • An arrayis an indexed list of values. • You can make an array of int, of double, of String,etc.All elements of an array must have the same type. 0 1 2 3 n-1 • This array contain n elements.
  • 30.
    Arrays • An arrayis noted using [] and is declared in the usual way: int values[]; // empty array int[] values; // equivalent declaration • To create an array of a given size, use the operator new : int values[] = new int[5]; • or you may use a variable to specify the size: int size = 12; int values[] = new int[size];
  • 31.
    Arrays • Array Initialization: •Curly braces can be used to initialize an array in the array declaration statement (and only there). int values[] = { 12, 24, -23, 47 }; • To access the elements of an array, use the [] operator: values[index] • Example: int values[] = { 12, 24, -23, 47 }; values[3] = 18; // write int x = values[1] + 3; // read
  • 32.
    Arrays • Each array has a length variable built-in that contains the length of the array. int values[] = new int[12]; int size = values.length; // 12 • Looping through an array • Example : int values[] = new int[5]; for (int i=0; i<values.length; i++) { values[i] = i; int y = values[i] *values[i]; System.out.println(y); } • Another one: double values[] = new double[25]; int j=0; while (j<values.length) {... j++; }
  • 33.
    Objects • Objects area collection of related data and methods. • Example: • Strings A string is a collection of characters (letters) and has a set of methods built in. String nextTrip = “Mexico”; int size = nextTrip.length(); // 6
  • 34.
    Objects • To createa new object, use the new operator. If you do not use new, you are making a reference to an object (i.e. a pointer to the same object). Point p; p.x = 23; p.y = -12; public static Point middlePoint (Point p1, Point p2) { Point q = new Point ((p1.x+p2.x)/2, (p1.y+p2.y)/2); return q; }
  • 35.
    Classes • A classis a prototype to design objects. • It is a set of variables and methods that encapsulates the properties of the class of objects. • In Java, you can (will) create several classes in project. • A class constructor is called each time an object of the class is instantiated (created).
  • 36.
    Packages • A packageis a set of classes that relate to a same purpose. • Example: math, graphics, input/output... • In order to use a package, you have to import it. package class class class object
  • 37.
    Object Oriented Programming •Objects are a collection of related data and methods. • To create a new object, use the new operator. If you do not use new, you are making a reference to an object (i.e a pointer to the same object).
  • 38.
    Objects and references Pointp1 = new Point (12,34); Point p2 = p1; System.out.println(“x = “ + p2.x); // 12 p1.x = 24; System.out.println(“x = “ + p2.x); // 24!
  • 39.
    The null object •null simply represents no object. It is convenient • as a return value to mean that a method failed for example. It may also be used to “remove” an element from an array. String values[] = { “ragab”, “ahmed”, “zidan” }; values[1] = null;
  • 40.
    Object methods v.s.class methods class Bicycle { static int gear, speed; public static void speedUp (Bicycle b) { b.speed += 10;} public static void main (String[] arguments) { Bicycle bike1 = new Bicycle(); speedUp (bike1); }} • static means that the variable is going to be same for all objects of the class. • Class methods are declared static. • static = the same for all objects • nonstatic = different for each object
  • 41.
    Abstraction • Objects aretools for abstraction. • Abstraction is a fundamental concept in computer science. • In Java, objects are instances of a class. • A class contains variables and methods that capture the essence of the object. • An object is instantiated using new
  • 42.
    Why is abstractionimportant? • Modularity (allows to subdivide a big problem into smaller sub-problems) • Powerful representation of real-world problems
  • 43.
    Inheritance • In theworld, people inherit characteristics from their parents. • In computer science, objects inherit variables and methods from their parents. • When you define a class in Java, you may define it as a subclass of another class (its parent).
  • 44.
    Why inheritance andit’s rules? • Avoid duplicate code • Improve modularity Inheritance rules • The subclass inherits all variables and methods • Use the extends keyword to indicate that one class inherits from another • Use the super keyword in the subclass constructor to call the parent constructor
  • 45.
  • 46.
    Example public class Vehicle { public int nWheels; // number of wheels public Vehicle (int n) {nWheels = n;} int getNWheels () {return nWheels;}} • ---------------------------------------- public class Car extends Vehicle { public Car (int n) {super (n);} public void openWindow() {} }
  • 47.
    Example public class Bicycle extends Vehicle { public Bicycle (int n) {super (n);} public void freeStyle() {} } • ------------------------------------- public class World { public static void main (String[] args) { Bicycle bike = new Bike (2); Car car = new Car (4); System.out.println (“Car has “ +car.getNWheels() + “ wheels”); System.out.println (“Bike has “ +bike.getNWheels() + “ wheels”);--
  • 48.
    OOP: Scope &Visibility • Scope: – A variable cannot be used outside of the curly braces (“,...-”) in which it is declared. – E.g., Class-level variables (fields) are usable everywhere in the class; loop variables are only usable in the scope of the loop
  • 49.
    OOP: Scope &Visibility • Visibility: – public fields, methods, & constructors can be “seen” or used directly by all classes & subclasses – protected fields, methods, & constructors can only be seen or used from within their class or subclasses – private fields, methods, & constructors can only be seen or used from within their exact class (in general, most or all of a class’s fields should be private) – Fields, methods, and constructors with unspecified (“default” or “package”) visibility can be seen by some classes – more on this later
  • 50.
    OOP: Getter &Setter Methods • Another way to access or modify fields • Good programming practice • Widely-used convention in Java • Also called accessors and mutators • Don’t come for free, but very useful when dealing with private or protected fields
  • 51.
    OOP: Ecapsulation • ThePrinciple of Encapsulation • Allows one to access and change the internals of a class, without having “direct access” • Visibility, Accessors, & Mutators are vital tools for this OOP principle
  • 52.
    OOP: this • Away for an instance of class to refer to itself – E.g.: say Engineer has a field called trafficHours and a setter method with this signature: – public void setTrafficHours(int trafficHours); – How to resolve scope? – Solution: use this.trafficHours = trafficHours; – this does not work inside static methods • Good programming practice • Standard Java convention • Does come for free, has many uses
  • 53.
    Inheritance & Abstraction •A class can extend another (single) class • Subclasses inherit methods and variables from their parents • This allows us to use objects to form an hierarchy of representations • Classifications of objects and relationships between them can now be modeled!
  • 54.
    Inheritance & Abstraction:TheObject class • Every class implicitly extends Object • So, in Java, every object is an Object… • “Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.” – from the Java API • Core and backbone of OOP in Java • Methods of note are equals(Object) and toString() – more on these later
  • 55.
    Inheritance & Abstraction:Overriding & Overloading • What if we want a subclass’s inherited method to do something different than that of its parent? – Override it! • What if we want multiple constructors for a class, or methods with the same name but different arguments? – Overload them!
  • 56.
    Inheritance & Abstraction:Overriding & Overloading • Overriding: re-defining an inherited method • E.g., Say every Manager gets a weekly bonus of amount weeklyBonus (which would be defined somewhere in the class) • To reflect this, we can override the weeklyPay() method simply by explicitly defining it again in Manager, with the desired changes
  • 57.
    Inheritance & Abstraction:Overriding & Overloading • Overloading: method or constructor with same name and type as another, but with a different signature (i.e., takes different number, ordering, or types of arguments) • Cannot have methods with same name and arguments and different return type
  • 58.
    Method Overriding • Methodoverriding occurs when a subclass implements a method that is already implemented in a superclass. The method name must be the same, and the parameter and return types of the subclass's implementation must be subtypes of the superclass's implementation. You cannot allow less access than the access level of the superclass's method. eg, class Timer { public Date getDate(Country c) { ... } } class USATimer { public Date getDate(USA usa) { ... } }
  • 59.
    Method Overloading • Methodoverloading is when two methods share the same name but have a different number or type of parameters. eg, public void print(String str) { ... } public void print(Date date) { ... }
  • 60.
    References • Java howto program, book. • Essential Java for scientists and Engineering, book. • MIT Lectures. • Tutorial from sun.