SlideShare a Scribd company logo
1 of 24
Download to read offline
Object-Oriented Programming:
               Classes and Objects in Java



Atit Patumvan
Faculty of Management and Information Sciences
Naresuan University




                                 http://atit.patumvan.com
2




                                                 Hello, World!!

      public class HelloWorld {
       public class HelloWorld {
              public static void main(String[] args) {
                public static void main(String[] args) {
                  System.out.println("Hello, World!!");
                   System.out.println("Hello, World!!");
              }
                }
      }
          }



      public class HelloWorld {
                                                           Hello, World!!
       public class HelloWorld {
              public HelloWorld(){
                public HelloWorld(){
                  System.out.println("Hello, World!!");
                   System.out.println("Hello, World!!");
              }
                }
              public static void main(String[] args) {
                public static void main(String[] args) {
                  new HelloWorld();
                   new HelloWorld();
              }
                }
      }
          }


                                                                   http://atit.patumvan.com
Object-Oriented Programming: Classes and Objects in Java
3




                                              Class Definition
                + BankAccount                   holder          + Customer

      -number : long                      0                1   -name : String
      -balance : double                                        +ssn : String

      +deposit(amount : double) : void
      +withdraw(amount : double) : void



      public class BankAccount {

          private long number;
          private double balance;                                        Properties
          public Customer holder;

          public void deposit(double amount) {
            balance += amount;
          }                                                                                         Class

          public void withdraw(double amount) {
            if (balance >= amount) {                                                  Methods
                balance -= amount;
            } else {
                System.out.println("System cannot process this transaction.");
            }
          }
      }
                                                                                       http://atit.patumvan.com
Object-Oriented Programming: Classes and Objects in Java
4




                                        Object Declaration
      A Class defines a data type that can be used to declare variables
        int number;
        BankAccount account;




           number                    int
                                                           account   BankAccount




                                                                                   http://atit.patumvan.com
Object-Oriented Programming: Classes and Objects in Java
5




                                             Object Creation
       ●   Objects are created with the new operator
       ●   To create an object means to allocate memory space for variables
       ●   New allocate memory for an object and return a reference to the object
       Int number;
       BankAccount account1;                               account1                        0x156F4H
                                                                      BankAccount
       number = 20;
       account1 = new BankAccount();                                  0x156F4H
       BankAccount account2 = new BankAccount();



                                                           account2                        0x15FFFH
                                                                      BankAccount
           number                    int
                                                                      0x15FFFH
                                           10

                                                                                    http://atit.patumvan.com
Object-Oriented Programming: Classes and Objects in Java
6




                                    Access to Properties
        BankAccount account;
        Customer customer;

        account = new BankAccount();
        customer = new Customer();                                    customer
                                                                                 Customer
        customer.name = “Bob Goodman”;
        customer.ssn = “2567893”;
                                                                                   number
        account.number = 23421;                                                                       long
        account.balance = 563948.50;
        account.holder = customer;                                                            23421

        System.out.println(“Owner: ”+account.holder.name);                         balance
        System.out.println(“Balance:”+account.balance);
                                                                                                    double
                                                                                             563948.50

                                                                                    holder
                                       Customer
            customer
                                          name
                                                             String
                                                 “Bob Goodman”
                                           ssn
                                                           String
                                                    “2567893”

                                                                                     http://atit.patumvan.com
Object-Oriented Programming: Classes and Objects in Java
7




                                                           Methods
        ●   Method are functions defined within a class
        ●   Methods can directly reference the variables of the class
        ●   Methods can only be invoked on object of the class to which they belong
        ●   During the execution of a method, invoked upon an object of class, the
            variables in the class take the value they have in object

        account2.deposit(1000);                              private double balance;
         account2.deposit(1000);                              private double balance;
                                                             public void deposit(double amount) {
                                                               public void deposit(double amount) {
                                                                 balance += amount;
                                                                  balance += amount;
                                                             }
                                                               }
                                                                                  account2.balance
                                                                                            http://atit.patumvan.com
Object-Oriented Programming: Classes and Objects in Java
8




            Method Calls from within a Method

       Method can directly invoke any other method of same class
        public class BankAccount {
         public class BankAccount {
          :
            :
          public void withdraw(double amount) {
            public void withdraw(double amount) {
              :
                :
          }
            }
                public void transfer(BankAccount target, double amount) {
                  public void transfer(BankAccount target, double amount) {
                    if (balance >= amount) {
                      if (balance >= amount) {
                        withdraw(amount);
                          withdraw(amount);
                        target.deposit(amount);
                          target.deposit(amount);
                    }
                      }
                }
                  }
        }
            }




                                                                              http://atit.patumvan.com
Object-Oriented Programming: Classes and Objects in Java
9




                                      Method Declaration
               Type of return value
                                                           Type of parameter variable

                                               Name of method            Name of parameter variable


  public static double cubeVolume(double sideLength){
    double volume = sideLength*sideLength*sideLength;                                            Method body
    return volume;
  }




                                                                                        http://atit.patumvan.com
Object-Oriented Programming: Classes and Objects in Java
10




     Parameter Passing and Return Value
      double length = 2;
       double length = 2;
      double result = cubeVolume(length);
       double result = cubeVolume(length);

                                  length
                                                                 result
                                                                                    8
                        parameter passing                  2    Return result
                           (copy value)                          (copy value)

                              sideLength                         volume

                                                           2   2*2*2→8              8


        public static double cubeVolume(double sideLength){
          public static double cubeVolume(double sideLength){
            double volume = sideLength*sideLength*sideLength;
             double volume = sideLength*sideLength*sideLength;
            return volume;
             return volume;
        }
          }
                                                                                http://atit.patumvan.com
Object-Oriented Programming: Classes and Objects in Java
11




                                                Variable Scope
       The scope of variable is the part of program in which you access it
        public class X {
         public class X {                                  Class X
          int a;
            int a;
          public void Y() {                                    int a;
            public void Y() {
               int b;
                int b;
                    If (...){ // branch Y1
                      If (...){ // branch Y1                      Method Y
                              int d;
                               int d;                                        branch Y1
                    } else { // branch Y2                         int b;
                      } else { // branch Y2
                              int e;                                            int d;
                               int e;
                    }
                      }
          }
            }                                                                branch Y2
                public void Z () {                                              int e;
                  public void Z () {
                    int c;
                      int c;
                    If (...) { // branch Z1
                      If (...) { // branch Z1
                        int f;
                          int f;
                    }
                      }                                           Method Z   Branch Z1
                }
                  }                                                             int f;
        }                                                         int c;
            }


                                                                                  http://atit.patumvan.com
Object-Oriented Programming: Classes and Objects in Java
12




                Accessors and Mutators Method
   public class Customer {
    public class Customer {
           private String name;
                                                           ●   Accessors is a method with in a
             private String name;
           private String ssn;
             private String ssn;
             :
               :
                                                               class designed to retrieve the
           public String getName() {

           }
             public String getName() {
               return name;
                 return name;                                  value of instance variable in that
             }
           public void setName(String name) {
             public void setName(String name) {
                                                               same class (get method)
               this.name = name;
                this.name = name;
           }
             }                                             ●    Accessors is a method with in a
           public String getSsn() {
             public String getSsn() {
           }
               return ssn;
                return ssn;                                    class designed to change the
             }
           public void setSsn(String ssn) {
             public void setSsn(String ssn) {                  value of instance variable in that
               this.ssn = ssn;
                this.ssn = ssn;
           }
            :
             }                                                 same class (set method)
              :
   }
       }

                                                                                    http://atit.patumvan.com
Object-Oriented Programming: Classes and Objects in Java
13




                                                    Constructor
        ●    “Methods” that are execute automatically when the object of class are
             created
        ●    Typical purpose
              ●    Initial values for the object of variables
              ●    Other initialization operation
        ●    Advantage
              ●    Syntax simplification
              ●    Encapsulation of object variables: avoid external access
                                                                              http://atit.patumvan.com
Object-Oriented Programming: Classes and Objects in Java
14




                                   Constructor Example
   public class BankAccount {
     public class BankAccount {
       :
         :
       public BankAccount(long num, Customer cus, double bal) {
         public BankAccount(long num, Customer cus, double bal) {
           number = num;
            number = num;
           holder = cus;                              public class Customer {
            holder = cus;                               public class Customer {
           balance = bal;
            balance = bal;
       }                                                  private String name;
         }                                                  private String name;
       :                                                  private String ssn;
         :                                                  private String ssn;
   }
     }
                                                          public Customer(String name, String ssn) {
                                                            public Customer(String name, String ssn) {
                                                              this.name = name;
                                                               this.name = name;
   public class Tester {                                      this.ssn = ssn;
     public class Tester {                                     this.ssn = ssn;
                                                          }
                                                            }
       public static void main(String[] args) {       }
         public static void main(String[] args) {       }
           BankAccount account;
            BankAccount account;
           Customer customer;
            Customer customer;
                   customer = new Customer("Bob Goodman", "2567893");
                    customer = new Customer("Bob Goodman", "2567893");
                   account = new BankAccount(23421, customer, 563948.50);
                    account = new BankAccount(23421, customer, 563948.50);
           }
               }
   }
       }

                                                                                  http://atit.patumvan.com
Object-Oriented Programming: Classes and Objects in Java
15




                                      Default Constructor
        ●    If no constructors are defined, Java defines one by default
              public class Customer {
               public class Customer {
                      private String name;
                       private String name;
                      private String ssn;
                       private String ssn;
                      public Customer() {
                        public Customer() {
                      }
                        }
              }
                  }


        ●    If a constructor is explicitly defined, The default constructor is not defined
              public class Customer {
                public class Customer {
                   :
                     :
                  public Customer(String name, String ssn) {
                    public Customer(String name, String ssn) {
                       :
                         :
                  }
                    }
              }
                }

                                                                           http://atit.patumvan.com
Object-Oriented Programming: Classes and Objects in Java
16




                                           The this Variable
        ●    Implicitly defined in the body of all methods
        ●    Reference to the object on which the method invoked
              public class Customer {
               public class Customer {
                      private String name;
                       private String name;
                      private String ssn;
                       private String ssn;
                      public Customer(String name, String ssn) {
                        public Customer(String name, String ssn) {
                          this.name = name;
                           this.name = name;
                          this.ssn = ssn;
                           this.ssn = ssn;
                      }
                        }
              }
                  }




                                                                     http://atit.patumvan.com
Object-Oriented Programming: Classes and Objects in Java
17




                                      this in Constructors
   public class BankAccount {
     public class BankAccount {
        :
          :
       public BankAccount(long num, Customer cus, double bal) {
         public BankAccount(long num, Customer cus, double bal) {
           number = num;
            number = num;              public class Customer {
           holder = cus;                 public class Customer {
            holder = cus;                    :
           balance = bal;                      :
            balance = bal;                 private BankAccount accounts[] = new BankAccount[20];
           cus.newAccount(this);             private BankAccount accounts[] = new BankAccount[20];
            cus.newAccount(this);          int nAccounts = 0;
       }                                     int nAccounts = 0;
         }
       :
         :                                 public void newAccount(BankAccount account) {
   }                                         public void newAccount(BankAccount account) {
     }                                         accounts[nAccounts++] = account;
                                                 accounts[nAccounts++] = account;
                                           }
                                             }
                                           :
                                             :
                                       }
                                         }

   Customer customer;
    Customer customer;
   customer = new Customer("Bob Goodman", "2567893");
    customer = new Customer("Bob Goodman", "2567893");
   new BankAccount(23421, customer, 563948.50);
    new BankAccount(23421, customer, 563948.50);
   new BankAccount(23421, customer, 789652.50);
    new BankAccount(23421, customer, 789652.50);


                                                                               http://atit.patumvan.com
Object-Oriented Programming: Classes and Objects in Java
18




                                                   Overloading
         :
           :
      public BankAccount(long num, Customer cus) {
        public BankAccount(long num, Customer cus) {
          number = num;
            number = num;
          holder = cus;
            holder = cus;
          cus.newAccount(this);
            cus.newAccount(this);
      }                                                            Constructor
        }
                                                                   Overloading
      public BankAccount(long num, Customer cus, double bal) {
        public BankAccount(long num, Customer cus, double bal) {
          number = num;
           number = num;
          holder = cus;
           holder = cus;
          balance = bal;
           balance = bal;
          cus.newAccount(this);
           cus.newAccount(this);
      }
        }
      public void deposit(int amount) {
        public void deposit(int amount) {
          balance += amount;
           balance += amount;
      }                                                            Method
        }
      public void deposit(double amount) {                         Overloading
        public void deposit(double amount) {
          balance += amount;
            balance += amount;
      }
        }
         :
           :
                                                                    http://atit.patumvan.com
Object-Oriented Programming: Classes and Objects in Java
19




                                                       Packages
        ●    Set of classes defined in a folder
        ●    Avoid symbol conflicts
        ●    Each class belongs to package
        ●    If no package is defined for a class, java includes it in the default
             package




                                                                           http://atit.patumvan.com
Object-Oriented Programming: Classes and Objects in Java
20




                                            Define Package
      graphicsCircle.java                                 graphicsrectangleRoundRectangle.java

      package graphics;                                     package graphics;
       package graphics;                                     package graphics;
      public class Circle {                                 public class RoundRectangle {
       public class Circle {                                 public class RoundRectangle {
              public void paint() {                                 public void paint() {
                public void paint() {                                 public void paint() {
                  :                                                     :
                    :                                                     :
              }                                                     }
                }                                                     }
      }                                                     }
          }                                                     }




                                                                                              http://atit.patumvan.com
Object-Oriented Programming: Classes and Objects in Java
21




        Using Class of a Different Package
      :
        :
      graphic.Circle c = new graphics.Circle();
                                                           ●   Automatically imported package
       graphic.Circle c = new graphics.Circle();
      c.paint();
       c.paint();
      :
        :                                                      ●   java.lang
      Import class
                                                               ●   DefaultPackage
      import graphics.Circle;
       import graphics.Circle;
        :
          :
        Circle c = new Circle();
          Circle c = new Circle();
                                                               ●   Current Package
        c.paint();
          c.paint();
        :
          :                                                ●   Packge name → folder structure
      Import all classes of package
      import graphics.*;
                                                           ●   CLASSPATH: list of folder where
       import graphics.*;
        :
          :
        Circle c = new Circle();
          Circle c = new Circle();                             java looks for package
        c.paint();
          c.paint();
        :
          :

                                                                                     http://atit.patumvan.com
Object-Oriented Programming: Classes and Objects in Java
22




                                              Access Control
     Package Same                                          Package Other

                                       subclass
                 Class                                          Subclass

               Package                                            Any



                                         Class                   Package   Subclass          Any

             public                        Yes                     Yes       Yes              Yes

         protected                        Yes                      Yes       Yes              No

            default                        Yes                     Yes       No               No

            private                        Yes                     No        No               No

                                                                                      http://atit.patumvan.com
Object-Oriented Programming: Classes and Objects in Java
23




                                             Static Members
                                                                         public class BankAccount {
        ●    Similar to global                                            public class BankAccount {
                                                                            private static long number = 0;
                                                                              private static long number = 0;
                                                                               :
                                                                                 :
        ●    Class member (static) vs. Instance                              public BankAccount(Customer cus) {
                                                                               public BankAccount(Customer cus) {
                                                                                 number++;
                                                                                   number++;
                                                                                 holder = cus;
             member (default)                                                      holder = cus;
                                                                                 cus.newAccount(this);
                                                                                   cus.newAccount(this);
                                                                             }
                                                                               }
                                                                               :
                                                                                 :
        ●    Static member belong to the class,                              public static long getNumber() {
                                                                               public static long getNumber() {
                                                                                 return number;
                                                                                   return number;
                                                                             }
             not to the objects                                                }
                                                                                :
                                                                                  :
                                                                         }
                                                                           }
        ●    Static member can be access from
             class or from object    BankAccount account = new BankAccount(customer);
                                      BankAccount account = new BankAccount(customer);
                                     long accountNumber = account.getNumber();
                                                             long accountNumber = account.getNumber();
                                                            :
                                                              :
                                                           long lastAccountNumber = BankAccount.getNumber();
                                                             long lastAccountNumber = BankAccount.getNumber();
                                                                                                 http://atit.patumvan.com
Object-Oriented Programming: Classes and Objects in Java
24




                                                final Variables
        ●    Similar to constant, there value cannot be changed
        ●    Initialization is mandatory
        ●    More efficient: static final
        ●    A constructor cannot be final

              public class Circle {
                public class Circle {
                  static final double PI = 3.141592653589793;
                    static final double PI = 3.141592653589793;
                  :
                    :
              }
                }




                                                                  http://atit.patumvan.com
Object-Oriented Programming: Classes and Objects in Java

More Related Content

Viewers also liked (8)

Inheritance
InheritanceInheritance
Inheritance
 
Java programming course for beginners
Java programming course for beginnersJava programming course for beginners
Java programming course for beginners
 
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
 
Java basic
Java basicJava basic
Java basic
 
Inheritance
InheritanceInheritance
Inheritance
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 

Similar to OOP: Classes and Objects

Flow-Centric, Back-In-Time Debugging
Flow-Centric, Back-In-Time DebuggingFlow-Centric, Back-In-Time Debugging
Flow-Centric, Back-In-Time Debugging
lienhard
 
The java class Account that simultes the Account class.pdf
   The java class Account that simultes  the Account class.pdf   The java class Account that simultes  the Account class.pdf
The java class Account that simultes the Account class.pdf
akshay1213
 
Please distinguish between the .h and .cpp file, create a fully work.pdf
Please distinguish between the .h and .cpp file, create a fully work.pdfPlease distinguish between the .h and .cpp file, create a fully work.pdf
Please distinguish between the .h and .cpp file, create a fully work.pdf
neerajsachdeva33
 
Tmpj3 01 201181102muhammad_tohir
Tmpj3 01 201181102muhammad_tohirTmpj3 01 201181102muhammad_tohir
Tmpj3 01 201181102muhammad_tohir
pencari buku
 

Similar to OOP: Classes and Objects (20)

Inheritance
InheritanceInheritance
Inheritance
 
While writing program in any language, you need to use various variables to s...
While writing program in any language, you need to use various variables to s...While writing program in any language, you need to use various variables to s...
While writing program in any language, you need to use various variables to s...
 
11-Classes.ppt
11-Classes.ppt11-Classes.ppt
11-Classes.ppt
 
Bank account in java
Bank account in javaBank account in java
Bank account in java
 
Class
ClassClass
Class
 
Flow-Centric, Back-In-Time Debugging
Flow-Centric, Back-In-Time DebuggingFlow-Centric, Back-In-Time Debugging
Flow-Centric, Back-In-Time Debugging
 
Oops
OopsOops
Oops
 
BANK MANAGEMENT SYSTEM report
BANK MANAGEMENT SYSTEM reportBANK MANAGEMENT SYSTEM report
BANK MANAGEMENT SYSTEM report
 
Improving application design with a rich domain model (springone 2007)
Improving application design with a rich domain model (springone 2007)Improving application design with a rich domain model (springone 2007)
Improving application design with a rich domain model (springone 2007)
 
IP project for class 12 cbse
IP project for class 12 cbseIP project for class 12 cbse
IP project for class 12 cbse
 
Cbsecomputersciencecclass12boardproject bankmanagmentsystem-180703065625-conv...
Cbsecomputersciencecclass12boardproject bankmanagmentsystem-180703065625-conv...Cbsecomputersciencecclass12boardproject bankmanagmentsystem-180703065625-conv...
Cbsecomputersciencecclass12boardproject bankmanagmentsystem-180703065625-conv...
 
The java class Account that simultes the Account class.pdf
   The java class Account that simultes  the Account class.pdf   The java class Account that simultes  the Account class.pdf
The java class Account that simultes the Account class.pdf
 
Please distinguish between the .h and .cpp file, create a fully work.pdf
Please distinguish between the .h and .cpp file, create a fully work.pdfPlease distinguish between the .h and .cpp file, create a fully work.pdf
Please distinguish between the .h and .cpp file, create a fully work.pdf
 
Introduction to aop
Introduction to aopIntroduction to aop
Introduction to aop
 
Class and object C++.pptx
Class and object C++.pptxClass and object C++.pptx
Class and object C++.pptx
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
Project on Bank System .docx
Project on Bank System .docxProject on Bank System .docx
Project on Bank System .docx
 
Seq uml
Seq umlSeq uml
Seq uml
 
Synthesizing API Usage Examples
Synthesizing API Usage Examples Synthesizing API Usage Examples
Synthesizing API Usage Examples
 
Tmpj3 01 201181102muhammad_tohir
Tmpj3 01 201181102muhammad_tohirTmpj3 01 201181102muhammad_tohir
Tmpj3 01 201181102muhammad_tohir
 

More from Atit Patumvan

แบบฝึกหัดวิชา Theory of Computation ชุดที่ 1 เซ็ต
แบบฝึกหัดวิชา Theory of Computation ชุดที่ 1 เซ็ตแบบฝึกหัดวิชา Theory of Computation ชุดที่ 1 เซ็ต
แบบฝึกหัดวิชา Theory of Computation ชุดที่ 1 เซ็ต
Atit Patumvan
 
Chapter 1 mathmatics tools
Chapter 1 mathmatics toolsChapter 1 mathmatics tools
Chapter 1 mathmatics tools
Atit Patumvan
 
Computer Programming Chapter 5 : Methods
Computer Programming Chapter 5 : MethodsComputer Programming Chapter 5 : Methods
Computer Programming Chapter 5 : Methods
Atit Patumvan
 
Computer Programming Chapter 4 : Loops
Computer Programming Chapter 4 : Loops Computer Programming Chapter 4 : Loops
Computer Programming Chapter 4 : Loops
Atit Patumvan
 
Introduction to Java EE (J2EE)
Introduction to Java EE (J2EE)Introduction to Java EE (J2EE)
Introduction to Java EE (J2EE)
Atit Patumvan
 

More from Atit Patumvan (20)

Iot for smart agriculture
Iot for smart agricultureIot for smart agriculture
Iot for smart agriculture
 
An Overview of eZee Burrp! (Philus Limited)
An Overview of eZee Burrp! (Philus Limited)An Overview of eZee Burrp! (Philus Limited)
An Overview of eZee Burrp! (Philus Limited)
 
แบบฝึกหัดวิชา Theory of Computation ชุดที่ 1 เซ็ต
แบบฝึกหัดวิชา Theory of Computation ชุดที่ 1 เซ็ตแบบฝึกหัดวิชา Theory of Computation ชุดที่ 1 เซ็ต
แบบฝึกหัดวิชา Theory of Computation ชุดที่ 1 เซ็ต
 
Chapter 1 mathmatics tools
Chapter 1 mathmatics toolsChapter 1 mathmatics tools
Chapter 1 mathmatics tools
 
Chapter 1 mathmatics tools
Chapter 1 mathmatics toolsChapter 1 mathmatics tools
Chapter 1 mathmatics tools
 
รายงานการประเมินคุณภาพภายใน ปีงบประมาณ 2556
รายงานการประเมินคุณภาพภายใน ปีงบประมาณ 2556รายงานการประเมินคุณภาพภายใน ปีงบประมาณ 2556
รายงานการประเมินคุณภาพภายใน ปีงบประมาณ 2556
 
Chapter 0 introduction to theory of computation
Chapter 0 introduction to theory of computationChapter 0 introduction to theory of computation
Chapter 0 introduction to theory of computation
 
Media literacy
Media literacyMedia literacy
Media literacy
 
Chapter 01 mathmatics tools (slide)
Chapter 01 mathmatics tools (slide)Chapter 01 mathmatics tools (slide)
Chapter 01 mathmatics tools (slide)
 
การบริหารเชิงคุณภาพ ชุดที่ 8
การบริหารเชิงคุณภาพ ชุดที่ 8การบริหารเชิงคุณภาพ ชุดที่ 8
การบริหารเชิงคุณภาพ ชุดที่ 8
 
การบริหารเชิงคุณภาพ ชุดที่ 7
การบริหารเชิงคุณภาพ ชุดที่ 7การบริหารเชิงคุณภาพ ชุดที่ 7
การบริหารเชิงคุณภาพ ชุดที่ 7
 
การบริหารเชิงคุณภาพ ชุดที่ 6
การบริหารเชิงคุณภาพ ชุดที่ 6การบริหารเชิงคุณภาพ ชุดที่ 6
การบริหารเชิงคุณภาพ ชุดที่ 6
 
Computer Programming Chapter 5 : Methods
Computer Programming Chapter 5 : MethodsComputer Programming Chapter 5 : Methods
Computer Programming Chapter 5 : Methods
 
Computer Programming Chapter 4 : Loops
Computer Programming Chapter 4 : Loops Computer Programming Chapter 4 : Loops
Computer Programming Chapter 4 : Loops
 
Introduction to Java EE (J2EE)
Introduction to Java EE (J2EE)Introduction to Java EE (J2EE)
Introduction to Java EE (J2EE)
 
การบริหารเชิงคุณภาพ ชุดที่ 5
การบริหารเชิงคุณภาพ ชุดที่ 5การบริหารเชิงคุณภาพ ชุดที่ 5
การบริหารเชิงคุณภาพ ชุดที่ 5
 
การบริหารเชิงคุณภาพ ชุดที่ 4
การบริหารเชิงคุณภาพ ชุดที่ 4การบริหารเชิงคุณภาพ ชุดที่ 4
การบริหารเชิงคุณภาพ ชุดที่ 4
 
การบริหารเชิงคุณภาพ ชุดที่ 3
การบริหารเชิงคุณภาพ ชุดที่ 3การบริหารเชิงคุณภาพ ชุดที่ 3
การบริหารเชิงคุณภาพ ชุดที่ 3
 
การบริหารเชิงคุณภาพ ชุดที่ 2
การบริหารเชิงคุณภาพ ชุดที่ 2การบริหารเชิงคุณภาพ ชุดที่ 2
การบริหารเชิงคุณภาพ ชุดที่ 2
 
Computer Programming: Chapter 1
Computer Programming: Chapter 1Computer Programming: Chapter 1
Computer Programming: Chapter 1
 

Recently uploaded

Dubai Call girls Service 0524076003 Call girls in Dubai
Dubai Call girls Service 0524076003 Call girls in DubaiDubai Call girls Service 0524076003 Call girls in Dubai
Dubai Call girls Service 0524076003 Call girls in Dubai
Monica Sydney
 
Haridwar Call Girls, 8699214473 Hot Girls Service Haridwar
Haridwar Call Girls, 8699214473 Hot Girls Service HaridwarHaridwar Call Girls, 8699214473 Hot Girls Service Haridwar
Haridwar Call Girls, 8699214473 Hot Girls Service Haridwar
ranekokila
 
Pakistani Call girls in Deira 0567006274 Deira Call girls
Pakistani Call girls in Deira 0567006274 Deira Call girlsPakistani Call girls in Deira 0567006274 Deira Call girls
Pakistani Call girls in Deira 0567006274 Deira Call girls
Monica Sydney
 
Models in Deira 0567006274 Deira Call girl Service
Models in Deira 0567006274 Deira Call girl ServiceModels in Deira 0567006274 Deira Call girl Service
Models in Deira 0567006274 Deira Call girl Service
Monica Sydney
 
Dubai Call girls Service 0524076003 Call girls services in Dubai
Dubai Call girls Service 0524076003 Call girls services in DubaiDubai Call girls Service 0524076003 Call girls services in Dubai
Dubai Call girls Service 0524076003 Call girls services in Dubai
Monica Sydney
 

Recently uploaded (20)

Deira call girls 0507330913 Call girls in Deira
Deira call girls 0507330913  Call girls in DeiraDeira call girls 0507330913  Call girls in Deira
Deira call girls 0507330913 Call girls in Deira
 
Call Girls Bhubaneswar 9777949614 call me Independent Escort Service Bhubaneswar
Call Girls Bhubaneswar 9777949614 call me Independent Escort Service BhubaneswarCall Girls Bhubaneswar 9777949614 call me Independent Escort Service Bhubaneswar
Call Girls Bhubaneswar 9777949614 call me Independent Escort Service Bhubaneswar
 
Dubai Call girls Service 0524076003 Call girls in Dubai
Dubai Call girls Service 0524076003 Call girls in DubaiDubai Call girls Service 0524076003 Call girls in Dubai
Dubai Call girls Service 0524076003 Call girls in Dubai
 
Call girls Service Dombivli - 9332606886 Our call girls are sure to provide y...
Call girls Service Dombivli - 9332606886 Our call girls are sure to provide y...Call girls Service Dombivli - 9332606886 Our call girls are sure to provide y...
Call girls Service Dombivli - 9332606886 Our call girls are sure to provide y...
 
📞 Contact Number 8617370543VIP Fatehgarh Call Girls
📞 Contact Number 8617370543VIP Fatehgarh Call Girls📞 Contact Number 8617370543VIP Fatehgarh Call Girls
📞 Contact Number 8617370543VIP Fatehgarh Call Girls
 
Haridwar Call Girls, 8699214473 Hot Girls Service Haridwar
Haridwar Call Girls, 8699214473 Hot Girls Service HaridwarHaridwar Call Girls, 8699214473 Hot Girls Service Haridwar
Haridwar Call Girls, 8699214473 Hot Girls Service Haridwar
 
Bhubaneswar🌹Call Girls Chandrashekharpur ❤Komal 9777949614 💟 Full Trusted CAL...
Bhubaneswar🌹Call Girls Chandrashekharpur ❤Komal 9777949614 💟 Full Trusted CAL...Bhubaneswar🌹Call Girls Chandrashekharpur ❤Komal 9777949614 💟 Full Trusted CAL...
Bhubaneswar🌹Call Girls Chandrashekharpur ❤Komal 9777949614 💟 Full Trusted CAL...
 
Kailashahar Call Girl Whatsapp Number 📞 8617370543 | Girls Number for Friend...
Kailashahar  Call Girl Whatsapp Number 📞 8617370543 | Girls Number for Friend...Kailashahar  Call Girl Whatsapp Number 📞 8617370543 | Girls Number for Friend...
Kailashahar Call Girl Whatsapp Number 📞 8617370543 | Girls Number for Friend...
 
Call Girls in Kollam - 9332606886 Our call girls are sure to provide you with...
Call Girls in Kollam - 9332606886 Our call girls are sure to provide you with...Call Girls in Kollam - 9332606886 Our call girls are sure to provide you with...
Call Girls in Kollam - 9332606886 Our call girls are sure to provide you with...
 
Hire 💕 8617370543 Kushinagar Call Girls Service Call Girls Agency
Hire 💕 8617370543 Kushinagar Call Girls Service Call Girls AgencyHire 💕 8617370543 Kushinagar Call Girls Service Call Girls Agency
Hire 💕 8617370543 Kushinagar Call Girls Service Call Girls Agency
 
Call Girls In Gandhinagar 📞 8617370543 At Low Cost Cash Payment Booking
Call Girls In Gandhinagar 📞 8617370543  At Low Cost Cash Payment BookingCall Girls In Gandhinagar 📞 8617370543  At Low Cost Cash Payment Booking
Call Girls In Gandhinagar 📞 8617370543 At Low Cost Cash Payment Booking
 
Pakistani Call girls in Deira 0567006274 Deira Call girls
Pakistani Call girls in Deira 0567006274 Deira Call girlsPakistani Call girls in Deira 0567006274 Deira Call girls
Pakistani Call girls in Deira 0567006274 Deira Call girls
 
Call girls Service Khammam - 9332606886 Rs 3000 Free Pickup & Drop Services 2...
Call girls Service Khammam - 9332606886 Rs 3000 Free Pickup & Drop Services 2...Call girls Service Khammam - 9332606886 Rs 3000 Free Pickup & Drop Services 2...
Call girls Service Khammam - 9332606886 Rs 3000 Free Pickup & Drop Services 2...
 
🌹Bhubaneswar🌹Ravi Tailkes ❤CALL GIRL 9777949614 ❤CALL GIRLS IN bhubaneswar E...
🌹Bhubaneswar🌹Ravi Tailkes  ❤CALL GIRL 9777949614 ❤CALL GIRLS IN bhubaneswar E...🌹Bhubaneswar🌹Ravi Tailkes  ❤CALL GIRL 9777949614 ❤CALL GIRLS IN bhubaneswar E...
🌹Bhubaneswar🌹Ravi Tailkes ❤CALL GIRL 9777949614 ❤CALL GIRLS IN bhubaneswar E...
 
Unnao 💋 Call Girl 8617370543 Call Girls in unnao Escort service book now
Unnao 💋 Call Girl 8617370543 Call Girls in unnao Escort service book nowUnnao 💋 Call Girl 8617370543 Call Girls in unnao Escort service book now
Unnao 💋 Call Girl 8617370543 Call Girls in unnao Escort service book now
 
Call Girls in Ernakulam - 9332606886 Our call girls are sure to provide you w...
Call Girls in Ernakulam - 9332606886 Our call girls are sure to provide you w...Call Girls in Ernakulam - 9332606886 Our call girls are sure to provide you w...
Call Girls in Ernakulam - 9332606886 Our call girls are sure to provide you w...
 
Models in Deira 0567006274 Deira Call girl Service
Models in Deira 0567006274 Deira Call girl ServiceModels in Deira 0567006274 Deira Call girl Service
Models in Deira 0567006274 Deira Call girl Service
 
Dubai Call girls Service 0524076003 Call girls services in Dubai
Dubai Call girls Service 0524076003 Call girls services in DubaiDubai Call girls Service 0524076003 Call girls services in Dubai
Dubai Call girls Service 0524076003 Call girls services in Dubai
 
Vip Call Girls Bhubaneswar 🐱‍🏍 9777949614 Independent Escorts Service Bhubane...
Vip Call Girls Bhubaneswar 🐱‍🏍 9777949614 Independent Escorts Service Bhubane...Vip Call Girls Bhubaneswar 🐱‍🏍 9777949614 Independent Escorts Service Bhubane...
Vip Call Girls Bhubaneswar 🐱‍🏍 9777949614 Independent Escorts Service Bhubane...
 
Call Girls South Tripura Just Call 8617370543 Top Class Call Girl Service Ava...
Call Girls South Tripura Just Call 8617370543 Top Class Call Girl Service Ava...Call Girls South Tripura Just Call 8617370543 Top Class Call Girl Service Ava...
Call Girls South Tripura Just Call 8617370543 Top Class Call Girl Service Ava...
 

OOP: Classes and Objects

  • 1. Object-Oriented Programming: Classes and Objects in Java Atit Patumvan Faculty of Management and Information Sciences Naresuan University http://atit.patumvan.com
  • 2. 2 Hello, World!! public class HelloWorld { public class HelloWorld { public static void main(String[] args) { public static void main(String[] args) { System.out.println("Hello, World!!"); System.out.println("Hello, World!!"); } } } } public class HelloWorld { Hello, World!! public class HelloWorld { public HelloWorld(){ public HelloWorld(){ System.out.println("Hello, World!!"); System.out.println("Hello, World!!"); } } public static void main(String[] args) { public static void main(String[] args) { new HelloWorld(); new HelloWorld(); } } } } http://atit.patumvan.com Object-Oriented Programming: Classes and Objects in Java
  • 3. 3 Class Definition + BankAccount holder + Customer -number : long 0 1 -name : String -balance : double +ssn : String +deposit(amount : double) : void +withdraw(amount : double) : void public class BankAccount { private long number; private double balance; Properties public Customer holder; public void deposit(double amount) { balance += amount; } Class public void withdraw(double amount) { if (balance >= amount) { Methods balance -= amount; } else { System.out.println("System cannot process this transaction."); } } } http://atit.patumvan.com Object-Oriented Programming: Classes and Objects in Java
  • 4. 4 Object Declaration A Class defines a data type that can be used to declare variables int number; BankAccount account; number int account BankAccount http://atit.patumvan.com Object-Oriented Programming: Classes and Objects in Java
  • 5. 5 Object Creation ● Objects are created with the new operator ● To create an object means to allocate memory space for variables ● New allocate memory for an object and return a reference to the object Int number; BankAccount account1; account1 0x156F4H BankAccount number = 20; account1 = new BankAccount(); 0x156F4H BankAccount account2 = new BankAccount(); account2 0x15FFFH BankAccount number int 0x15FFFH 10 http://atit.patumvan.com Object-Oriented Programming: Classes and Objects in Java
  • 6. 6 Access to Properties BankAccount account; Customer customer; account = new BankAccount(); customer = new Customer(); customer Customer customer.name = “Bob Goodman”; customer.ssn = “2567893”; number account.number = 23421; long account.balance = 563948.50; account.holder = customer; 23421 System.out.println(“Owner: ”+account.holder.name); balance System.out.println(“Balance:”+account.balance); double 563948.50 holder Customer customer name String “Bob Goodman” ssn String “2567893” http://atit.patumvan.com Object-Oriented Programming: Classes and Objects in Java
  • 7. 7 Methods ● Method are functions defined within a class ● Methods can directly reference the variables of the class ● Methods can only be invoked on object of the class to which they belong ● During the execution of a method, invoked upon an object of class, the variables in the class take the value they have in object account2.deposit(1000); private double balance; account2.deposit(1000); private double balance; public void deposit(double amount) { public void deposit(double amount) { balance += amount; balance += amount; } } account2.balance http://atit.patumvan.com Object-Oriented Programming: Classes and Objects in Java
  • 8. 8 Method Calls from within a Method Method can directly invoke any other method of same class public class BankAccount { public class BankAccount { : : public void withdraw(double amount) { public void withdraw(double amount) { : : } } public void transfer(BankAccount target, double amount) { public void transfer(BankAccount target, double amount) { if (balance >= amount) { if (balance >= amount) { withdraw(amount); withdraw(amount); target.deposit(amount); target.deposit(amount); } } } } } } http://atit.patumvan.com Object-Oriented Programming: Classes and Objects in Java
  • 9. 9 Method Declaration Type of return value Type of parameter variable Name of method Name of parameter variable public static double cubeVolume(double sideLength){ double volume = sideLength*sideLength*sideLength; Method body return volume; } http://atit.patumvan.com Object-Oriented Programming: Classes and Objects in Java
  • 10. 10 Parameter Passing and Return Value double length = 2; double length = 2; double result = cubeVolume(length); double result = cubeVolume(length); length result 8 parameter passing 2 Return result (copy value) (copy value) sideLength volume 2 2*2*2→8 8 public static double cubeVolume(double sideLength){ public static double cubeVolume(double sideLength){ double volume = sideLength*sideLength*sideLength; double volume = sideLength*sideLength*sideLength; return volume; return volume; } } http://atit.patumvan.com Object-Oriented Programming: Classes and Objects in Java
  • 11. 11 Variable Scope The scope of variable is the part of program in which you access it public class X { public class X { Class X int a; int a; public void Y() { int a; public void Y() { int b; int b; If (...){ // branch Y1 If (...){ // branch Y1 Method Y int d; int d; branch Y1 } else { // branch Y2 int b; } else { // branch Y2 int e; int d; int e; } } } } branch Y2 public void Z () { int e; public void Z () { int c; int c; If (...) { // branch Z1 If (...) { // branch Z1 int f; int f; } } Method Z Branch Z1 } } int f; } int c; } http://atit.patumvan.com Object-Oriented Programming: Classes and Objects in Java
  • 12. 12 Accessors and Mutators Method public class Customer { public class Customer { private String name; ● Accessors is a method with in a private String name; private String ssn; private String ssn; : : class designed to retrieve the public String getName() { } public String getName() { return name; return name; value of instance variable in that } public void setName(String name) { public void setName(String name) { same class (get method) this.name = name; this.name = name; } } ● Accessors is a method with in a public String getSsn() { public String getSsn() { } return ssn; return ssn; class designed to change the } public void setSsn(String ssn) { public void setSsn(String ssn) { value of instance variable in that this.ssn = ssn; this.ssn = ssn; } : } same class (set method) : } } http://atit.patumvan.com Object-Oriented Programming: Classes and Objects in Java
  • 13. 13 Constructor ● “Methods” that are execute automatically when the object of class are created ● Typical purpose ● Initial values for the object of variables ● Other initialization operation ● Advantage ● Syntax simplification ● Encapsulation of object variables: avoid external access http://atit.patumvan.com Object-Oriented Programming: Classes and Objects in Java
  • 14. 14 Constructor Example public class BankAccount { public class BankAccount { : : public BankAccount(long num, Customer cus, double bal) { public BankAccount(long num, Customer cus, double bal) { number = num; number = num; holder = cus; public class Customer { holder = cus; public class Customer { balance = bal; balance = bal; } private String name; } private String name; : private String ssn; : private String ssn; } } public Customer(String name, String ssn) { public Customer(String name, String ssn) { this.name = name; this.name = name; public class Tester { this.ssn = ssn; public class Tester { this.ssn = ssn; } } public static void main(String[] args) { } public static void main(String[] args) { } BankAccount account; BankAccount account; Customer customer; Customer customer; customer = new Customer("Bob Goodman", "2567893"); customer = new Customer("Bob Goodman", "2567893"); account = new BankAccount(23421, customer, 563948.50); account = new BankAccount(23421, customer, 563948.50); } } } } http://atit.patumvan.com Object-Oriented Programming: Classes and Objects in Java
  • 15. 15 Default Constructor ● If no constructors are defined, Java defines one by default public class Customer { public class Customer { private String name; private String name; private String ssn; private String ssn; public Customer() { public Customer() { } } } } ● If a constructor is explicitly defined, The default constructor is not defined public class Customer { public class Customer { : : public Customer(String name, String ssn) { public Customer(String name, String ssn) { : : } } } } http://atit.patumvan.com Object-Oriented Programming: Classes and Objects in Java
  • 16. 16 The this Variable ● Implicitly defined in the body of all methods ● Reference to the object on which the method invoked public class Customer { public class Customer { private String name; private String name; private String ssn; private String ssn; public Customer(String name, String ssn) { public Customer(String name, String ssn) { this.name = name; this.name = name; this.ssn = ssn; this.ssn = ssn; } } } } http://atit.patumvan.com Object-Oriented Programming: Classes and Objects in Java
  • 17. 17 this in Constructors public class BankAccount { public class BankAccount { : : public BankAccount(long num, Customer cus, double bal) { public BankAccount(long num, Customer cus, double bal) { number = num; number = num; public class Customer { holder = cus; public class Customer { holder = cus; : balance = bal; : balance = bal; private BankAccount accounts[] = new BankAccount[20]; cus.newAccount(this); private BankAccount accounts[] = new BankAccount[20]; cus.newAccount(this); int nAccounts = 0; } int nAccounts = 0; } : : public void newAccount(BankAccount account) { } public void newAccount(BankAccount account) { } accounts[nAccounts++] = account; accounts[nAccounts++] = account; } } : : } } Customer customer; Customer customer; customer = new Customer("Bob Goodman", "2567893"); customer = new Customer("Bob Goodman", "2567893"); new BankAccount(23421, customer, 563948.50); new BankAccount(23421, customer, 563948.50); new BankAccount(23421, customer, 789652.50); new BankAccount(23421, customer, 789652.50); http://atit.patumvan.com Object-Oriented Programming: Classes and Objects in Java
  • 18. 18 Overloading : : public BankAccount(long num, Customer cus) { public BankAccount(long num, Customer cus) { number = num; number = num; holder = cus; holder = cus; cus.newAccount(this); cus.newAccount(this); } Constructor } Overloading public BankAccount(long num, Customer cus, double bal) { public BankAccount(long num, Customer cus, double bal) { number = num; number = num; holder = cus; holder = cus; balance = bal; balance = bal; cus.newAccount(this); cus.newAccount(this); } } public void deposit(int amount) { public void deposit(int amount) { balance += amount; balance += amount; } Method } public void deposit(double amount) { Overloading public void deposit(double amount) { balance += amount; balance += amount; } } : : http://atit.patumvan.com Object-Oriented Programming: Classes and Objects in Java
  • 19. 19 Packages ● Set of classes defined in a folder ● Avoid symbol conflicts ● Each class belongs to package ● If no package is defined for a class, java includes it in the default package http://atit.patumvan.com Object-Oriented Programming: Classes and Objects in Java
  • 20. 20 Define Package graphicsCircle.java graphicsrectangleRoundRectangle.java package graphics; package graphics; package graphics; package graphics; public class Circle { public class RoundRectangle { public class Circle { public class RoundRectangle { public void paint() { public void paint() { public void paint() { public void paint() { : : : : } } } } } } } } http://atit.patumvan.com Object-Oriented Programming: Classes and Objects in Java
  • 21. 21 Using Class of a Different Package : : graphic.Circle c = new graphics.Circle(); ● Automatically imported package graphic.Circle c = new graphics.Circle(); c.paint(); c.paint(); : : ● java.lang Import class ● DefaultPackage import graphics.Circle; import graphics.Circle; : : Circle c = new Circle(); Circle c = new Circle(); ● Current Package c.paint(); c.paint(); : : ● Packge name → folder structure Import all classes of package import graphics.*; ● CLASSPATH: list of folder where import graphics.*; : : Circle c = new Circle(); Circle c = new Circle(); java looks for package c.paint(); c.paint(); : : http://atit.patumvan.com Object-Oriented Programming: Classes and Objects in Java
  • 22. 22 Access Control Package Same Package Other subclass Class Subclass Package Any Class Package Subclass Any public Yes Yes Yes Yes protected Yes Yes Yes No default Yes Yes No No private Yes No No No http://atit.patumvan.com Object-Oriented Programming: Classes and Objects in Java
  • 23. 23 Static Members public class BankAccount { ● Similar to global public class BankAccount { private static long number = 0; private static long number = 0; : : ● Class member (static) vs. Instance public BankAccount(Customer cus) { public BankAccount(Customer cus) { number++; number++; holder = cus; member (default) holder = cus; cus.newAccount(this); cus.newAccount(this); } } : : ● Static member belong to the class, public static long getNumber() { public static long getNumber() { return number; return number; } not to the objects } : : } } ● Static member can be access from class or from object BankAccount account = new BankAccount(customer); BankAccount account = new BankAccount(customer); long accountNumber = account.getNumber(); long accountNumber = account.getNumber(); : : long lastAccountNumber = BankAccount.getNumber(); long lastAccountNumber = BankAccount.getNumber(); http://atit.patumvan.com Object-Oriented Programming: Classes and Objects in Java
  • 24. 24 final Variables ● Similar to constant, there value cannot be changed ● Initialization is mandatory ● More efficient: static final ● A constructor cannot be final public class Circle { public class Circle { static final double PI = 3.141592653589793; static final double PI = 3.141592653589793; : : } } http://atit.patumvan.com Object-Oriented Programming: Classes and Objects in Java