SlideShare a Scribd company logo
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

More Related Content

What's hot

03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
Java generics
Java genericsJava generics
Java generics
Hosein Zare
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
Intro C# Book
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
Intro C# Book
 
07. Arrays
07. Arrays07. Arrays
07. Arrays
Intro C# Book
 
06.Loops
06.Loops06.Loops
06.Loops
Intro C# Book
 
02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and Variables
Intro C# Book
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity
Intro C# Book
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
Jim Roepcke
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
Intro C# Book
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
Intro C# Book
 
On Parameterised Types and Java Generics
On Parameterised Types and Java GenericsOn Parameterised Types and Java Generics
On Parameterised Types and Java Generics
Yann-Gaël Guéhéneuc
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and Pitfalls
Rakesh Waghela
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 
Front end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreFront end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreWeb Zhao
 
DSA 103 Object Oriented Programming :: Week 5
DSA 103 Object Oriented Programming :: Week 5DSA 103 Object Oriented Programming :: Week 5
DSA 103 Object Oriented Programming :: Week 5
Ferdin Joe John Joseph PhD
 

What's hot (20)

03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
Java generics
Java genericsJava generics
Java generics
 
Java Day-6
Java Day-6Java Day-6
Java Day-6
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
07. Arrays
07. Arrays07. Arrays
07. Arrays
 
Java Day-5
Java Day-5Java Day-5
Java Day-5
 
06.Loops
06.Loops06.Loops
06.Loops
 
02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and Variables
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
 
On Parameterised Types and Java Generics
On Parameterised Types and Java GenericsOn Parameterised Types and Java Generics
On Parameterised Types and Java Generics
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and Pitfalls
 
Java Day-7
Java Day-7Java Day-7
Java Day-7
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
 
Front end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreFront end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript core
 
DSA 103 Object Oriented Programming :: Week 5
DSA 103 Object Oriented Programming :: Week 5DSA 103 Object Oriented Programming :: Week 5
DSA 103 Object Oriented Programming :: Week 5
 
Java generics final
Java generics finalJava generics final
Java generics final
 

Similar to Java introduction

Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
Akash Pandey
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basics
LovelitJose
 
4java Basic Syntax
4java Basic Syntax4java Basic Syntax
4java Basic SyntaxAdil Jafri
 
Data types and Operators
Data types and OperatorsData types and Operators
Data types and Operators
raksharao
 
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfLECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
ShashikantSathe3
 
02basics
02basics02basics
02basics
Waheed Warraich
 
Introduction to c#
Introduction to c#Introduction to c#
CAP615-Unit1.pptx
CAP615-Unit1.pptxCAP615-Unit1.pptx
CAP615-Unit1.pptx
SatyajeetGaur3
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#
Rohit Rao
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Generics
GenericsGenerics
6 arrays injava
6 arrays injava6 arrays injava
6 arrays injavairdginfo
 
LECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdfLECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdf
SHASHIKANT346021
 
LECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdfLECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdf
ShashikantSathe3
 
Java
Java Java
Introduction to Java Programming Part 2
Introduction to Java Programming Part 2Introduction to Java Programming Part 2
Introduction to Java Programming Part 2
university of education,Lahore
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.
supriyasarkar38
 
Functional Operations - Susan Potter
Functional Operations - Susan PotterFunctional Operations - Susan Potter
Functional Operations - Susan Potter
distributed matters
 
Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_reviewEdureka!
 

Similar to Java introduction (20)

Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basics
 
4java Basic Syntax
4java Basic Syntax4java Basic Syntax
4java Basic Syntax
 
Data types and Operators
Data types and OperatorsData types and Operators
Data types and Operators
 
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfLECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
 
02basics
02basics02basics
02basics
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 
CAP615-Unit1.pptx
CAP615-Unit1.pptxCAP615-Unit1.pptx
CAP615-Unit1.pptx
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Generics
GenericsGenerics
Generics
 
6 arrays injava
6 arrays injava6 arrays injava
6 arrays injava
 
Core java
Core javaCore java
Core java
 
LECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdfLECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdf
 
LECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdfLECTURE 3 LOOPS, ARRAYS.pdf
LECTURE 3 LOOPS, ARRAYS.pdf
 
Java
Java Java
Java
 
Introduction to Java Programming Part 2
Introduction to Java Programming Part 2Introduction to Java Programming Part 2
Introduction to Java Programming Part 2
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.
 
Functional Operations - Susan Potter
Functional Operations - Susan PotterFunctional Operations - Susan Potter
Functional Operations - Susan Potter
 
Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_review
 

Recently uploaded

Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
Steve Thomason
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
bennyroshan06
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
AzmatAli747758
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
rosedainty
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
Fundacja Rozwoju Społeczeństwa Przedsiębiorczego
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
PedroFerreira53928
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
Celine George
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
Nguyen Thanh Tu Collection
 

Recently uploaded (20)

Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 

Java introduction

  • 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 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.
  • 5. 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”.
  • 6. 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.
  • 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 • 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.
  • 9. 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.
  • 10. 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"); } }
  • 11. Basics of Java • Program Structure class CLASSNAME { public static void main(String[] args) { STATEMENTS } }
  • 12. 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); } }
  • 13. 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;
  • 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
  • 15. 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))
  • 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 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.
  • 26. 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.
  • 27. 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
  • 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 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.
  • 30. 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];
  • 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 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
  • 34. 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; }
  • 35. 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).
  • 36. 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
  • 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 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!
  • 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 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
  • 42. Why is abstraction important? • Modularity (allows to subdivide a big problem into smaller sub-problems) • Powerful representation of real-world problems
  • 43. 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).
  • 44. 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
  • 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 • 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
  • 52. 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
  • 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: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
  • 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 • 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) { ... } }
  • 59. 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) { ... }
  • 60. References • Java how to program, book. • Essential Java for scientists and Engineering, book. • MIT Lectures. • Tutorial from sun.