SlideShare a Scribd company logo
Developing Applications
   for Android

    Muhammad Usman Chaudhry
         SZABIST CS4615




                              Lecture # 2
Today - OOP Revision
    ● Classes & Obejcts Overview
    ● Nested Classes
       ○ Static nested & Inner classes
       ○ Local & anonymous classes
    ● Inheritance
    ● Method Overriding & Dynamic Polymorphism
    ● Abstraction
    ● Interfaces
    ● Packages
    ● Annotations & Javadocs




Muhammad Usman Chaudhry       CS4615             SZABIST
Today - Design Patterns
    ●   Design Patterns Overview
    ●   Context Pattern
    ●   Adapter Pattern
    ●   Separation of Concerns
        ○ Model-View-Controller




Muhammad Usman Chaudhry       CS4615   SZABIST
Classes & Objects
    ● Coming code example will explain:
         ○   Classes
         ○   Objects
         ○   Encapsulation
         ○   Constructors
         ○   Class Members & Methods
         ○   Instance Members & Methods
         ○   Entry Point
         ○   Getter & Setters




Muhammad Usman Chaudhry        CS4615     SZABIST
//Student.java
class Student{      Access
                    Modifier           Attribute
  private String studentName;
                                    Static
  private static int count;         Member
                    Not Recommended                         Setter
  public void setStudentName(String _studentName){
     if(!_studentName.equals("")) this.studentName = _studentName;
  }
                                                                     Validation
                                              Getter
  public String getStudentName(){
    return this.studentName;
  }
                                                         Instance
                                                         Method
  public String getEncodedUrlForStudentName(){
      return UrlEncoder.encode(this.getStudentName(),"UTF-8");
  }
  ...

Muhammad Usman Chaudhry              CS4615                               SZABIST
...
                                                Class Method
    public static int getCount(){
        return Student.count;
    }
                                          Default Constructor
    public Student(){
                                        Calling 1-argument
      this("No Name");                  constructor
    }                                                    1-argument
    public Student(String studentName){                  Constructor
      this.setStudentName(studentName);
    }                                                        Entry Point
    public static void main(String[] args){
                                                      Object of Type
      Student stduent = new Student();
                                                      Student
      String name = student.getName();
      int count = Student.getCount();                 Instance Method
                                                      Call
    }
}                                                     Class Method Call



Muhammad Usman Chaudhry                CS4615                              SZABIST
Nested Classes
    ● Java allows defining class within another class.
    ● Nested classes are divided into 2 more
      categories:
      ○ Static Nested Classes (Declared Static)
      ○ Inner Nested Classes (Non-static)
         ■ Local Classes
         ■ Anonymous Classes
      ○ Both Inner & Static nested classes have
         member scope.
    ● Examples & Uses are in coming slides.

Muhammad Usman Chaudhry   CS4615                    SZABIST
Example: Static & Inner Nested Classes
//Outer class can only be public or package-private
class OuterClass{
   private int someVariable;
   //Modifier can be private, protected, public or package-private
   static class StaticNestedClass{
      //Cannot access private members of outer class directly.
   }
   class InnerClass{
      //Can access private members of outer class
      OuterClass oc = OuterClass.this; // implicit reference available
      int a = oc.someVariable; //can be done
      int b = OuterClass.this.someVariable; //is another way to access...
   }
   //Cannot declare static members within inner nested class.
}




Muhammad Usman Chaudhry                           CS4615                    SZABIST
Example: Accessing Nested Inner Class

//Accessing Nested Inner Class
OuterClass oc = new OuterClass(); //Either create new object or use previous instance
OuterClass.InnerClass innerClassObject = oc.new InnerClass(); //Way#1
OuterClass.InnerClass innerClassObject = new OuterClass().new InnerClass(); //Way#2




    ● Way#1 is using previous instance so all
      values of the object of outer class will be
      intact and accessible via inner class.
    ● Way#2 is creating new instance of outer
      class as well.

Muhammad Usman Chaudhry                  CS4615                                  SZABIST
Example: Accessing Nested Static Class

//Accessing Nested Static Class
OuterClass.StaticNestedClass sncObj = new OuterClass.StaticNestedClass();




● As simple as creating the normal object. No
  added syntax.




Muhammad Usman Chaudhry                 CS4615                              SZABIST
Local & Anonymous Inner Classes
    ● Inner class within 'body' of a method is
      known as local inner class.
    ● Inner class within 'body' of a method
      without naming it is known as anonymous
      inner class.
    ● Scope of local inner class is local to
      function.
    ● Scope of anonymous inner class is only to
      the point where it's declared.

Muhammad Usman Chaudhry   CS4615                  SZABIST
Example: Local Inner Class

class OuterClass{
   private int someVariable;
   public OuterClass(){
      //Local inner classes don't specify access modifiers
      class LocalInnerClass{
         public void myInnerMethod(){
           //implicit reference available to access members of outer class...
           int count = OuterClass.this.someVariable;
         }
      }
     LocalInnerClass lic = new LocalInnerClass();
     lic.myInnerMethod();
   }
}




Muhammad Usman Chaudhry                     CS4615                              SZABIST
Example: Anonymous Inner Class

  public void someFunction(){        class RunnableThread implements Runnable{
    new Thread(new Runnable(){          RunnableThread(){
       @Override                        //do something in constructor
       public void run(){               }
          //do something here...        public void run(){
       }                                  //do something here...
    }).start();                         }
  }                                  }
                                     .
                                     .
                                     //To access it
                                     RunnableThread myThread = new RunnableThread();
                                     new Thread(myThread).start();



                   ●    Left (Anonymous) Vs Right (Normal)
                   ●    No clutter in coding


Muhammad Usman Chaudhry                   CS4615                                       SZABIST
Why Use Nested Classes
    ● Logically grouping classes together.
    ● Increase encapsulation.
    ● Clean coding.




Muhammad Usman Chaudhry   CS4615             SZABIST
Important
    ● Java don't have anything exactly similar to
      Objective-C or .Net delegates, the closest
      thing is anonymous inner class which are
      used instead of delegates.
    ● The main trick is to create an interface
      with a single function and then implement
      it via anonymous inner class.



Muhammad Usman Chaudhry   CS4615                SZABIST
Inheritance
    ● When you want to create a new class and there is
      already a class that includes some of the code that you
      want, you can derive your new class from the existing
      class.
    ● A class that is derived from another class is called sub-
      class, inherited class (derived, extended, child etc.)
    ● Java does support multi-level inheritance.
    ● There is no support for multiple inheritance in Java
      and every class can extend up to one class at a time.
    ● Lets go through examples in next slides.



Muhammad Usman Chaudhry       CS4615                        SZABIST
//A bicycle class : Example taken from Oracle Docs...
public class Bicycle {
  public int cadence; public int gear; public int speed;
  public Bicycle(int startCadence, int startSpeed, int startGear) {
     gear = startGear;
     cadence = startCadence;
     speed = startSpeed;
  }
   public void setCadence(int newValue) {
     cadence = newValue;
  }
  public void setGear(int newValue) {
     gear = newValue;
  }
  public void applyBrake(int decrement) {
     speed -= decrement;
  }
  public void speedUp(int increment) {
     speed += increment;
  }
}




Muhammad Usman Chaudhry                          CS4615               SZABIST
public class MountainBike extends Bicycle {
  // the MountainBike subclass adds
  // one field
  public int seatHeight;

    // the MountainBike subclass has one
    // constructor
    public MountainBike(int startHeight,
                 int startCadence,
                 int startSpeed,
                 int startGear) {
       super(startCadence, startSpeed, startGear);
       seatHeight = startHeight;
    }

    // the MountainBike subclass adds
    // one method
    public void setHeight(int newValue) {
       seatHeight = newValue;
    }
}




Muhammad Usman Chaudhry                          CS4615   SZABIST
Method Overriding & Dynamic Polymorphism

    ● Redefining superclass method in subclass.
    ● An instance method in subclass with the same signature
      (name, number, type of params & return type) as instance
      method in superclass overrides the superclass's method.
    ● We may access the functionality of methods and members
      of super class via 'super' keyword.
    ● In case reference variable is calling an overridden method
      the method to be invoked is determined by the object, your
      reference variable is pointing to. (dynamic polymorphism).
    ● Examples to follow in coming slides.




Muhammad Usman Chaudhry        CS4615                        SZABIST
//Class professional                         //Calling all
class Professional {                         Professional p = new Professional();
   public String name;
   public Professional(){
                                             Programmer prog = new Programmer();
   }
   public boolean isDisciplined(){
     //professional level implementations    p.isDisciplined();//Normal call
   }
}                                            //First professional is called, then
                                             //programmer's isDisciplined is called.
//Class programmer                           prog.isDisciplined();
class Programmer extends Professional{
   public Programmer(){
                                             //without super.isDisciplined() statement
   }
   @Override                                 //calling prog.isDisciplined(); will only call
   public boolean isDisciplined(){           //programmer's isDisciplined() method.
     //professional rules also apply
     super.isDisciplined();                  //dynamic polymorphism
     //programmer level implementations      Professional pr = new Programmer();
   }
                                             pr.isDisciplined();
}




Muhammad Usman Chaudhry                     CS4615                                        SZABIST
Abstraction
    ● An abstract class cannot be instantiated.
    ● Abstract class can be subclassed.
    ● An abstract method, only has signatures.
    ● If any class has abstract methods it must be declared
      abstract itself.
    ● Subclass must implement all the abstract methods of
      abstract class otherwise it must be declared abstract
      as well.
    ● Abstract class may also contain abstract methods.
    ● Examples in next slides.



Muhammad Usman Chaudhry      CS4615                       SZABIST
//Abstract class example               //Implementation
abstract class GraphicObject {         class Circle extends GraphicObject {
  int x;                                  void draw() {
  int y;
                                             //circle specific implementation
  void moveTo(int newX, int newY) {
     //some implementation
                                          }
  }                                       void resize() {
  abstract void draw();                      //circle specific resize
  abstract void resize();                 }
}                                      }
                                       class Rectangle extends GraphicObject {
                                          void draw() {
                                             //rectangle specific implementation
                                          }
                                          void resize() {
                                             //rectangle specific resizing
                                          }
                                       }




Muhammad Usman Chaudhry               CS4615                                   SZABIST
Interfaces
    ● Interfaces are implemented by other classes
      and extended by other interfaces.
    ● Unlike class inheritance an interface can
      extend multiple interfaces.
    ● Interface body contains signatures only.
    ● All methods in an interface are implicitly
      public.
    ● Example to follow.


Muhammad Usman Chaudhry   CS4615              SZABIST
//Interface example                    //Implementation
public Interface GraphicInterface {    class Circle implements GraphicInterface {
  void draw();                            void draw() {
  void resize();
                                             //circle specific implementation
}
                                          }
                                          void resize() {
                                             //circle specific resize
                                          }
                                       }
                                       class Rectangle extends GraphicInterface {
                                          void draw() {
                                             //rectangle specific implementation
                                          }
                                          void resize() {
                                             //rectangle specific resizing
                                          }
                                       }




Muhammad Usman Chaudhry               CS4615                                 SZABIST
Abstract Class Vs Interface
    ● Abstract class can contain fields that are
      not static & final.
    ● Similarly abstract class can contain
      implementations, while interface is
      signature only.
    ● One class can implement multiple
      interfaces. While the same class cannot
      extend multiple abstract classes.


Muhammad Usman Chaudhry   CS4615                   SZABIST
Packages
    ● Grouping similar classes together is called
      package.
    ● It's similar to that of namespace in .Net
    ● An example would be custom controls
      related classes are in controls package, or
      graphics related classes in graphics package
      etc.
    ● import statement is used to include
      packages.
    ● Examples to follow.
Muhammad Usman Chaudhry   CS4615                SZABIST
//Package example
//Sample package
package net.thepaksoft.appname; //current package

//all graphics related customized classes
import net.thepaksoft.appname.graphics.*;

//ListView class
import net.thepaksoft.appname.controls.ListView;




Muhammad Usman Chaudhry    CS4615                   SZABIST
Annotations & Javadocs
    ● Annotation provide data about code, they
      don't have direct impact over it.
    ● Annotations are mostly used for:
         ○ Information for compiler. //Suppress warnings etc.
         ○ Compile time & deploy time processing.//Code generation.
         ○ Runtime processing.//Examination at runtime
    ● Annotations are used in comments for
      Javadocs to generate automatic
      documentation against code.
    ● Examples to follow.

Muhammad Usman Chaudhry           CS4615                          SZABIST
// Javadoc comment follows
   /**
    * @deprecated
    * explanation of why it
    * was deprecated
    */
   @Deprecated
   static void deprecatedMethod() { }
}

// mark method as a superclass method
  // that has been overridden
  @Override
  int overriddenMethod() { }
// use a deprecated method and tell
  // compiler not to generate a warning
  @SuppressWarnings("deprecation")
   void useDeprecatedMethod() {
      // deprecation warning
      // - suppressed
      objectOne.deprecatedMethod();
   }




Muhammad Usman Chaudhry                   CS4615   SZABIST
Design Patterns
    ● They're used to solve the common problems.
    ● Classical design patterns include 3 categories and 23
      patterns:
      ○ Creational - Deals with creation of object.
      ○ Structural - Deals with structure of object/class.
      ○ Behavioral - Communication between objects
    ● Bad patterns or approaches are known as anti-
      patterns as well.
    ● There are 100s of other patterns.
    ● We'll study the most relevant and commonly used
      under android.


Muhammad Usman Chaudhry      CS4615                     SZABIST
Context Pattern in Android
    ● Interface to global information about application
      environment.
    ● It maintains current state of application/object.
    ● Mostly used to get information about other part of
      program.
    ● Used to access standard common resources.
    ● Used to access components implicitly.
    ● Implemented by Android System to provide access to
      application specific resources and classes.




Muhammad Usman Chaudhry     CS4615                     SZABIST
Context Pattern in Android
    ● We may get context by invoking any of these:
         ○   getApplicationContext()
         ○   getContext()
         ○   getBaseContext()
         ○   this (Current activity)
    ● And use above like:
         ○   ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(),...);
         ○   getApplicationContext().getSharedPreference(name,mode);




Muhammad Usman Chaudhry                      CS4615                                        SZABIST
Adapter Pattern in Android
    ●   Aimed at binding view with data.
    ●   When your data changes your view changes as well.
    ●   No need to add/update data one by one into the view.
    ●   Android have following implementations for Adapter:
        ○ BaseAdapter inherits Adapter implements
           ListAdapter, SpinnerAdapter
         ○ ArrayAdatper
         ○ ResrouceCursorAdapter




Muhammad Usman Chaudhry       CS4615                      SZABIST
Adapter Pattern Android (Code)

ArrayList<HashMap> myList = new ArrayList<HashMap>();
String[] data = new String[] { "line1","line2" } ;
int[] idList = new int[] { R.id.text1, R.id.text2 } ;
SimpleAdapter dataToView = new SimpleAdapter(this,
myList, R.layout.two_lines, data, idList);
setListAdapter( dataToView );




Muhammad Usman Chaudhry   CS4615                    SZABIST
Separation of Concerns
    ● Appropriate layered approach
    ● Separate Presentation, Business Logic, from
      Design
    ● Partial classes, under Smalltalk, .Net &
      Ruby
    ● MVC, MVP, MVVM etc. Patterns




Muhammad Usman Chaudhry   CS4615               SZABIST
MVC - Model-View-Controller
    ● UI Presentation pattern
    ● Separates View (UI) from Model (Business
      Logic)
    ● Separation of Concerns:
         ○ View is responsible for rendering UI.
         ○ Model is responsible for business behavior.
         ○ Controller is responsible for responding to UI
           Actions & communication between Model & View.
    ● All 3 can directly communicate with each
      other.

Muhammad Usman Chaudhry       CS4615                    SZABIST
MVC - Model-View-Controller
    ● Implementations as discussed in previous
      slides exist in many web frameworks like
      Rails & Yii etc.
    ● Implementation varies in some frameworks
      like Cocoa Touch, where:
         ○ Controller is used as communication bridge
           between Model & Views, as mentioned previously
           but Models & Views cannot communicate directly.
         ○ Views don't have knowledge of Model.
         ○ Models have no knowledge of Views.


Muhammad Usman Chaudhry       CS4615                     SZABIST
MVC in Android
    ● MVC is kind of built into Android
    ● You may create as many 'Model' classes you
      like to represent the business data.
    ● 'Views' are there in form of XML Layouts.
    ● 'Controllers' are there in form of Activity
      classes.




Muhammad Usman Chaudhry   CS4615               SZABIST
That's All for Today
    ● Have great vacations & Eid Mubarak!




Muhammad Usman Chaudhry   CS4615            SZABIST
Coming Up Next Week
    ● Dive into Android.
         ○   Hello World
         ○   SDK
         ○   File Organization
         ○   AVD
         ○   DDMS
         ○   LogCat
         ○   Debugging
         ○   Manifest
         ○   And Much more...
    ● Totally interactive class.

Muhammad Usman Chaudhry          CS4615   SZABIST

More Related Content

What's hot

Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Javabackdoor
 
Java
Java Java
Inner Classes
Inner Classes Inner Classes
Inner Classes
Hitesh-Java
 
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Sagar Verma
 
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Soumen Santra
 
Java OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - InheritanceJava OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - Inheritance
OUM SAOKOSAL
 
Inheritance
InheritanceInheritance
Inheritance
piyush Kumar Sharma
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute
 
Java Programming - 05 access control in java
Java Programming - 05 access control in javaJava Programming - 05 access control in java
Java Programming - 05 access control in java
Danairat Thanabodithammachari
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
Java OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and ObjectJava OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and Object
OUM SAOKOSAL
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesSunil Kumar Gunasekaran
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 
OOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and InterfacesOOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and Interfaces
Hitesh-Java
 
‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3
Mahmoud Alfarra
 
03class
03class03class

What's hot (19)

Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
 
Java
Java Java
Java
 
Inner Classes
Inner Classes Inner Classes
Inner Classes
 
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2
 
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
 
Java OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - InheritanceJava OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Java Programming - 05 access control in java
Java Programming - 05 access control in javaJava Programming - 05 access control in java
Java Programming - 05 access control in java
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Java OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and ObjectJava OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and Object
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Java oop
Java oopJava oop
Java oop
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
OOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and InterfacesOOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and Interfaces
 
‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3
 
03class
03class03class
03class
 

Similar to Developing Applications for Android - Lecture#2

OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
Shalabh Chaudhary
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
Rosie Jane Enomar
 
Session 21 - Inner Classes
Session 21 - Inner ClassesSession 21 - Inner Classes
Session 21 - Inner Classes
PawanMM
 
Java Programming inner and Nested classes.pptx
Java Programming inner and Nested classes.pptxJava Programming inner and Nested classes.pptx
Java Programming inner and Nested classes.pptx
AkashJha84
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptx
RAJASEKHARV10
 
BCA Class and Object (3).pptx
BCA Class and Object (3).pptxBCA Class and Object (3).pptx
BCA Class and Object (3).pptx
SarthakSrivastava70
 
Lecture 4 part 1.pdf
Lecture 4 part 1.pdfLecture 4 part 1.pdf
Lecture 4 part 1.pdf
SakhilejasonMsibi
 
Java Methods
Java MethodsJava Methods
Java Methods
Rosmina Joy Cabauatan
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptx
akila m
 
03_Objects and Classes in java.pdf
03_Objects and Classes in java.pdf03_Objects and Classes in java.pdf
03_Objects and Classes in java.pdf
Parameshwar Maddela
 
Core Java
Core JavaCore Java
Core Java
Khasim Saheb
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
Elizabeth alexander
 
Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)
Abu Saleh
 
OOP and java by a introduction sandesh sharma
OOP and java by a introduction sandesh sharmaOOP and java by a introduction sandesh sharma
OOP and java by a introduction sandesh sharma
Sandesh Sharma
 
Core java concepts
Core java concepts Core java concepts
Core java concepts
javeed_mhd
 
Inner classes ,annoumous and outer classes in java
Inner classes ,annoumous and outer classes in javaInner classes ,annoumous and outer classes in java
Inner classes ,annoumous and outer classes in java
Adil Mehmoood
 

Similar to Developing Applications for Android - Lecture#2 (20)

OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
Session 21 - Inner Classes
Session 21 - Inner ClassesSession 21 - Inner Classes
Session 21 - Inner Classes
 
javainheritance
javainheritancejavainheritance
javainheritance
 
Java Programming inner and Nested classes.pptx
Java Programming inner and Nested classes.pptxJava Programming inner and Nested classes.pptx
Java Programming inner and Nested classes.pptx
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptx
 
BCA Class and Object (3).pptx
BCA Class and Object (3).pptxBCA Class and Object (3).pptx
BCA Class and Object (3).pptx
 
Lecture 4 part 1.pdf
Lecture 4 part 1.pdfLecture 4 part 1.pdf
Lecture 4 part 1.pdf
 
Java Methods
Java MethodsJava Methods
Java Methods
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptx
 
Java Basic day-2
Java Basic day-2Java Basic day-2
Java Basic day-2
 
03_Objects and Classes in java.pdf
03_Objects and Classes in java.pdf03_Objects and Classes in java.pdf
03_Objects and Classes in java.pdf
 
Core Java
Core JavaCore Java
Core Java
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
 
Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)
 
OOP and java by a introduction sandesh sharma
OOP and java by a introduction sandesh sharmaOOP and java by a introduction sandesh sharma
OOP and java by a introduction sandesh sharma
 
Lecture 6.pptx
Lecture 6.pptxLecture 6.pptx
Lecture 6.pptx
 
Core java concepts
Core java concepts Core java concepts
Core java concepts
 
Inner classes ,annoumous and outer classes in java
Inner classes ,annoumous and outer classes in javaInner classes ,annoumous and outer classes in java
Inner classes ,annoumous and outer classes in java
 
7 inheritance
7 inheritance7 inheritance
7 inheritance
 

Recently uploaded

GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 

Recently uploaded (20)

GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 

Developing Applications for Android - Lecture#2

  • 1. Developing Applications for Android Muhammad Usman Chaudhry SZABIST CS4615 Lecture # 2
  • 2. Today - OOP Revision ● Classes & Obejcts Overview ● Nested Classes ○ Static nested & Inner classes ○ Local & anonymous classes ● Inheritance ● Method Overriding & Dynamic Polymorphism ● Abstraction ● Interfaces ● Packages ● Annotations & Javadocs Muhammad Usman Chaudhry CS4615 SZABIST
  • 3. Today - Design Patterns ● Design Patterns Overview ● Context Pattern ● Adapter Pattern ● Separation of Concerns ○ Model-View-Controller Muhammad Usman Chaudhry CS4615 SZABIST
  • 4. Classes & Objects ● Coming code example will explain: ○ Classes ○ Objects ○ Encapsulation ○ Constructors ○ Class Members & Methods ○ Instance Members & Methods ○ Entry Point ○ Getter & Setters Muhammad Usman Chaudhry CS4615 SZABIST
  • 5. //Student.java class Student{ Access Modifier Attribute private String studentName; Static private static int count; Member Not Recommended Setter public void setStudentName(String _studentName){ if(!_studentName.equals("")) this.studentName = _studentName; } Validation Getter public String getStudentName(){ return this.studentName; } Instance Method public String getEncodedUrlForStudentName(){ return UrlEncoder.encode(this.getStudentName(),"UTF-8"); } ... Muhammad Usman Chaudhry CS4615 SZABIST
  • 6. ... Class Method public static int getCount(){ return Student.count; } Default Constructor public Student(){ Calling 1-argument this("No Name"); constructor } 1-argument public Student(String studentName){ Constructor this.setStudentName(studentName); } Entry Point public static void main(String[] args){ Object of Type Student stduent = new Student(); Student String name = student.getName(); int count = Student.getCount(); Instance Method Call } } Class Method Call Muhammad Usman Chaudhry CS4615 SZABIST
  • 7. Nested Classes ● Java allows defining class within another class. ● Nested classes are divided into 2 more categories: ○ Static Nested Classes (Declared Static) ○ Inner Nested Classes (Non-static) ■ Local Classes ■ Anonymous Classes ○ Both Inner & Static nested classes have member scope. ● Examples & Uses are in coming slides. Muhammad Usman Chaudhry CS4615 SZABIST
  • 8. Example: Static & Inner Nested Classes //Outer class can only be public or package-private class OuterClass{ private int someVariable; //Modifier can be private, protected, public or package-private static class StaticNestedClass{ //Cannot access private members of outer class directly. } class InnerClass{ //Can access private members of outer class OuterClass oc = OuterClass.this; // implicit reference available int a = oc.someVariable; //can be done int b = OuterClass.this.someVariable; //is another way to access... } //Cannot declare static members within inner nested class. } Muhammad Usman Chaudhry CS4615 SZABIST
  • 9. Example: Accessing Nested Inner Class //Accessing Nested Inner Class OuterClass oc = new OuterClass(); //Either create new object or use previous instance OuterClass.InnerClass innerClassObject = oc.new InnerClass(); //Way#1 OuterClass.InnerClass innerClassObject = new OuterClass().new InnerClass(); //Way#2 ● Way#1 is using previous instance so all values of the object of outer class will be intact and accessible via inner class. ● Way#2 is creating new instance of outer class as well. Muhammad Usman Chaudhry CS4615 SZABIST
  • 10. Example: Accessing Nested Static Class //Accessing Nested Static Class OuterClass.StaticNestedClass sncObj = new OuterClass.StaticNestedClass(); ● As simple as creating the normal object. No added syntax. Muhammad Usman Chaudhry CS4615 SZABIST
  • 11. Local & Anonymous Inner Classes ● Inner class within 'body' of a method is known as local inner class. ● Inner class within 'body' of a method without naming it is known as anonymous inner class. ● Scope of local inner class is local to function. ● Scope of anonymous inner class is only to the point where it's declared. Muhammad Usman Chaudhry CS4615 SZABIST
  • 12. Example: Local Inner Class class OuterClass{ private int someVariable; public OuterClass(){ //Local inner classes don't specify access modifiers class LocalInnerClass{ public void myInnerMethod(){ //implicit reference available to access members of outer class... int count = OuterClass.this.someVariable; } } LocalInnerClass lic = new LocalInnerClass(); lic.myInnerMethod(); } } Muhammad Usman Chaudhry CS4615 SZABIST
  • 13. Example: Anonymous Inner Class public void someFunction(){ class RunnableThread implements Runnable{ new Thread(new Runnable(){ RunnableThread(){ @Override //do something in constructor public void run(){ } //do something here... public void run(){ } //do something here... }).start(); } } } . . //To access it RunnableThread myThread = new RunnableThread(); new Thread(myThread).start(); ● Left (Anonymous) Vs Right (Normal) ● No clutter in coding Muhammad Usman Chaudhry CS4615 SZABIST
  • 14. Why Use Nested Classes ● Logically grouping classes together. ● Increase encapsulation. ● Clean coding. Muhammad Usman Chaudhry CS4615 SZABIST
  • 15. Important ● Java don't have anything exactly similar to Objective-C or .Net delegates, the closest thing is anonymous inner class which are used instead of delegates. ● The main trick is to create an interface with a single function and then implement it via anonymous inner class. Muhammad Usman Chaudhry CS4615 SZABIST
  • 16. Inheritance ● When you want to create a new class and there is already a class that includes some of the code that you want, you can derive your new class from the existing class. ● A class that is derived from another class is called sub- class, inherited class (derived, extended, child etc.) ● Java does support multi-level inheritance. ● There is no support for multiple inheritance in Java and every class can extend up to one class at a time. ● Lets go through examples in next slides. Muhammad Usman Chaudhry CS4615 SZABIST
  • 17. //A bicycle class : Example taken from Oracle Docs... public class Bicycle { public int cadence; public int gear; public int speed; public Bicycle(int startCadence, int startSpeed, int startGear) { gear = startGear; cadence = startCadence; speed = startSpeed; } public void setCadence(int newValue) { cadence = newValue; } public void setGear(int newValue) { gear = newValue; } public void applyBrake(int decrement) { speed -= decrement; } public void speedUp(int increment) { speed += increment; } } Muhammad Usman Chaudhry CS4615 SZABIST
  • 18. public class MountainBike extends Bicycle { // the MountainBike subclass adds // one field public int seatHeight; // the MountainBike subclass has one // constructor public MountainBike(int startHeight, int startCadence, int startSpeed, int startGear) { super(startCadence, startSpeed, startGear); seatHeight = startHeight; } // the MountainBike subclass adds // one method public void setHeight(int newValue) { seatHeight = newValue; } } Muhammad Usman Chaudhry CS4615 SZABIST
  • 19. Method Overriding & Dynamic Polymorphism ● Redefining superclass method in subclass. ● An instance method in subclass with the same signature (name, number, type of params & return type) as instance method in superclass overrides the superclass's method. ● We may access the functionality of methods and members of super class via 'super' keyword. ● In case reference variable is calling an overridden method the method to be invoked is determined by the object, your reference variable is pointing to. (dynamic polymorphism). ● Examples to follow in coming slides. Muhammad Usman Chaudhry CS4615 SZABIST
  • 20. //Class professional //Calling all class Professional { Professional p = new Professional(); public String name; public Professional(){ Programmer prog = new Programmer(); } public boolean isDisciplined(){ //professional level implementations p.isDisciplined();//Normal call } } //First professional is called, then //programmer's isDisciplined is called. //Class programmer prog.isDisciplined(); class Programmer extends Professional{ public Programmer(){ //without super.isDisciplined() statement } @Override //calling prog.isDisciplined(); will only call public boolean isDisciplined(){ //programmer's isDisciplined() method. //professional rules also apply super.isDisciplined(); //dynamic polymorphism //programmer level implementations Professional pr = new Programmer(); } pr.isDisciplined(); } Muhammad Usman Chaudhry CS4615 SZABIST
  • 21. Abstraction ● An abstract class cannot be instantiated. ● Abstract class can be subclassed. ● An abstract method, only has signatures. ● If any class has abstract methods it must be declared abstract itself. ● Subclass must implement all the abstract methods of abstract class otherwise it must be declared abstract as well. ● Abstract class may also contain abstract methods. ● Examples in next slides. Muhammad Usman Chaudhry CS4615 SZABIST
  • 22. //Abstract class example //Implementation abstract class GraphicObject { class Circle extends GraphicObject { int x; void draw() { int y; //circle specific implementation void moveTo(int newX, int newY) { //some implementation } } void resize() { abstract void draw(); //circle specific resize abstract void resize(); } } } class Rectangle extends GraphicObject { void draw() { //rectangle specific implementation } void resize() { //rectangle specific resizing } } Muhammad Usman Chaudhry CS4615 SZABIST
  • 23. Interfaces ● Interfaces are implemented by other classes and extended by other interfaces. ● Unlike class inheritance an interface can extend multiple interfaces. ● Interface body contains signatures only. ● All methods in an interface are implicitly public. ● Example to follow. Muhammad Usman Chaudhry CS4615 SZABIST
  • 24. //Interface example //Implementation public Interface GraphicInterface { class Circle implements GraphicInterface { void draw(); void draw() { void resize(); //circle specific implementation } } void resize() { //circle specific resize } } class Rectangle extends GraphicInterface { void draw() { //rectangle specific implementation } void resize() { //rectangle specific resizing } } Muhammad Usman Chaudhry CS4615 SZABIST
  • 25. Abstract Class Vs Interface ● Abstract class can contain fields that are not static & final. ● Similarly abstract class can contain implementations, while interface is signature only. ● One class can implement multiple interfaces. While the same class cannot extend multiple abstract classes. Muhammad Usman Chaudhry CS4615 SZABIST
  • 26. Packages ● Grouping similar classes together is called package. ● It's similar to that of namespace in .Net ● An example would be custom controls related classes are in controls package, or graphics related classes in graphics package etc. ● import statement is used to include packages. ● Examples to follow. Muhammad Usman Chaudhry CS4615 SZABIST
  • 27. //Package example //Sample package package net.thepaksoft.appname; //current package //all graphics related customized classes import net.thepaksoft.appname.graphics.*; //ListView class import net.thepaksoft.appname.controls.ListView; Muhammad Usman Chaudhry CS4615 SZABIST
  • 28. Annotations & Javadocs ● Annotation provide data about code, they don't have direct impact over it. ● Annotations are mostly used for: ○ Information for compiler. //Suppress warnings etc. ○ Compile time & deploy time processing.//Code generation. ○ Runtime processing.//Examination at runtime ● Annotations are used in comments for Javadocs to generate automatic documentation against code. ● Examples to follow. Muhammad Usman Chaudhry CS4615 SZABIST
  • 29. // Javadoc comment follows /** * @deprecated * explanation of why it * was deprecated */ @Deprecated static void deprecatedMethod() { } } // mark method as a superclass method // that has been overridden @Override int overriddenMethod() { } // use a deprecated method and tell // compiler not to generate a warning @SuppressWarnings("deprecation") void useDeprecatedMethod() { // deprecation warning // - suppressed objectOne.deprecatedMethod(); } Muhammad Usman Chaudhry CS4615 SZABIST
  • 30. Design Patterns ● They're used to solve the common problems. ● Classical design patterns include 3 categories and 23 patterns: ○ Creational - Deals with creation of object. ○ Structural - Deals with structure of object/class. ○ Behavioral - Communication between objects ● Bad patterns or approaches are known as anti- patterns as well. ● There are 100s of other patterns. ● We'll study the most relevant and commonly used under android. Muhammad Usman Chaudhry CS4615 SZABIST
  • 31. Context Pattern in Android ● Interface to global information about application environment. ● It maintains current state of application/object. ● Mostly used to get information about other part of program. ● Used to access standard common resources. ● Used to access components implicitly. ● Implemented by Android System to provide access to application specific resources and classes. Muhammad Usman Chaudhry CS4615 SZABIST
  • 32. Context Pattern in Android ● We may get context by invoking any of these: ○ getApplicationContext() ○ getContext() ○ getBaseContext() ○ this (Current activity) ● And use above like: ○ ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(),...); ○ getApplicationContext().getSharedPreference(name,mode); Muhammad Usman Chaudhry CS4615 SZABIST
  • 33. Adapter Pattern in Android ● Aimed at binding view with data. ● When your data changes your view changes as well. ● No need to add/update data one by one into the view. ● Android have following implementations for Adapter: ○ BaseAdapter inherits Adapter implements ListAdapter, SpinnerAdapter ○ ArrayAdatper ○ ResrouceCursorAdapter Muhammad Usman Chaudhry CS4615 SZABIST
  • 34. Adapter Pattern Android (Code) ArrayList<HashMap> myList = new ArrayList<HashMap>(); String[] data = new String[] { "line1","line2" } ; int[] idList = new int[] { R.id.text1, R.id.text2 } ; SimpleAdapter dataToView = new SimpleAdapter(this, myList, R.layout.two_lines, data, idList); setListAdapter( dataToView ); Muhammad Usman Chaudhry CS4615 SZABIST
  • 35. Separation of Concerns ● Appropriate layered approach ● Separate Presentation, Business Logic, from Design ● Partial classes, under Smalltalk, .Net & Ruby ● MVC, MVP, MVVM etc. Patterns Muhammad Usman Chaudhry CS4615 SZABIST
  • 36. MVC - Model-View-Controller ● UI Presentation pattern ● Separates View (UI) from Model (Business Logic) ● Separation of Concerns: ○ View is responsible for rendering UI. ○ Model is responsible for business behavior. ○ Controller is responsible for responding to UI Actions & communication between Model & View. ● All 3 can directly communicate with each other. Muhammad Usman Chaudhry CS4615 SZABIST
  • 37. MVC - Model-View-Controller ● Implementations as discussed in previous slides exist in many web frameworks like Rails & Yii etc. ● Implementation varies in some frameworks like Cocoa Touch, where: ○ Controller is used as communication bridge between Model & Views, as mentioned previously but Models & Views cannot communicate directly. ○ Views don't have knowledge of Model. ○ Models have no knowledge of Views. Muhammad Usman Chaudhry CS4615 SZABIST
  • 38. MVC in Android ● MVC is kind of built into Android ● You may create as many 'Model' classes you like to represent the business data. ● 'Views' are there in form of XML Layouts. ● 'Controllers' are there in form of Activity classes. Muhammad Usman Chaudhry CS4615 SZABIST
  • 39. That's All for Today ● Have great vacations & Eid Mubarak! Muhammad Usman Chaudhry CS4615 SZABIST
  • 40. Coming Up Next Week ● Dive into Android. ○ Hello World ○ SDK ○ File Organization ○ AVD ○ DDMS ○ LogCat ○ Debugging ○ Manifest ○ And Much more... ● Totally interactive class. Muhammad Usman Chaudhry CS4615 SZABIST