Developing Applications   for Android    Muhammad Usman Chaudhry         SZABIST CS4615                              Lectu...
Today - OOP Revision    ● Classes & Obejcts Overview    ● Nested Classes       ○ Static nested & Inner classes       ○ Loc...
Today - Design Patterns    ●   Design Patterns Overview    ●   Context Pattern    ●   Adapter Pattern    ●   Separation of...
Classes & Objects    ● Coming code example will explain:         ○   Classes         ○   Objects         ○   Encapsulation...
//Student.javaclass Student{      Access                    Modifier           Attribute  private String studentName;     ...
...                                                Class Method    public static int getCount(){        return Student.cou...
Nested Classes    ● Java allows defining class within another class.    ● Nested classes are divided into 2 more      cate...
Example: Static & Inner Nested Classes//Outer class can only be public or package-privateclass OuterClass{   private int s...
Example: Accessing Nested Inner Class//Accessing Nested Inner ClassOuterClass oc = new OuterClass(); //Either create new o...
Example: Accessing Nested Static Class//Accessing Nested Static ClassOuterClass.StaticNestedClass sncObj = new OuterClass....
Local & Anonymous Inner Classes    ● Inner class within body of a method is      known as local inner class.    ● Inner cl...
Example: Local Inner Classclass OuterClass{   private int someVariable;   public OuterClass(){      //Local inner classes ...
Example: Anonymous Inner Class  public void someFunction(){        class RunnableThread implements Runnable{    new Thread...
Why Use Nested Classes    ● Logically grouping classes together.    ● Increase encapsulation.    ● Clean coding.Muhammad U...
Important    ● Java dont have anything exactly similar to      Objective-C or .Net delegates, the closest      thing is an...
Inheritance    ● When you want to create a new class and there is      already a class that includes some of the code that...
//A bicycle class : Example taken from Oracle Docs...public class Bicycle {  public int cadence; public int gear; public i...
public class MountainBike extends Bicycle {  // the MountainBike subclass adds  // one field  public int seatHeight;    //...
Method Overriding & Dynamic Polymorphism    ● Redefining superclass method in subclass.    ● An instance method in subclas...
//Class professional                         //Calling allclass Professional {                         Professional p = ne...
Abstraction    ● An abstract class cannot be instantiated.    ● Abstract class can be subclassed.    ● An abstract method,...
//Abstract class example               //Implementationabstract class GraphicObject {         class Circle extends Graphic...
Interfaces    ● Interfaces are implemented by other classes      and extended by other interfaces.    ● Unlike class inher...
//Interface example                    //Implementationpublic Interface GraphicInterface {    class Circle implements Grap...
Abstract Class Vs Interface    ● Abstract class can contain fields that are      not static & final.    ● Similarly abstra...
Packages    ● Grouping similar classes together is called      package.    ● Its similar to that of namespace in .Net    ●...
//Package example//Sample packagepackage net.thepaksoft.appname; //current package//all graphics related customized classe...
Annotations & Javadocs    ● Annotation provide data about code, they      dont have direct impact over it.    ● Annotation...
// Javadoc comment follows   /**    * @deprecated    * explanation of why it    * was deprecated    */   @Deprecated   sta...
Design Patterns    ● Theyre used to solve the common problems.    ● Classical design patterns include 3 categories and 23 ...
Context Pattern in Android    ● Interface to global information about application      environment.    ● It maintains curr...
Context Pattern in Android    ● We may get context by invoking any of these:         ○   getApplicationContext()         ○...
Adapter Pattern in Android    ●   Aimed at binding view with data.    ●   When your data changes your view changes as well...
Adapter Pattern Android (Code)ArrayList<HashMap> myList = new ArrayList<HashMap>();String[] data = new String[] { "line1",...
Separation of Concerns    ● Appropriate layered approach    ● Separate Presentation, Business Logic, from      Design    ●...
MVC - Model-View-Controller    ● UI Presentation pattern    ● Separates View (UI) from Model (Business      Logic)    ● Se...
MVC - Model-View-Controller    ● Implementations as discussed in previous      slides exist in many web frameworks like   ...
MVC in Android    ● MVC is kind of built into Android    ● You may create as many Model classes you      like to represent...
Thats 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         ...
Upcoming SlideShare
Loading in …5
×

Developing Applications for Android - Lecture#2

1,323 views

Published on

Slides from course, Developing Applications for Android, CS4615, SZABIST, Karachi.

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,323
On SlideShare
0
From Embeds
0
Number of Embeds
15
Actions
Shares
0
Downloads
122
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Developing Applications for Android - Lecture#2

  1. 1. Developing Applications for Android Muhammad Usman Chaudhry SZABIST CS4615 Lecture # 2
  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 & JavadocsMuhammad Usman Chaudhry CS4615 SZABIST
  3. 3. Today - Design Patterns ● Design Patterns Overview ● Context Pattern ● Adapter Pattern ● Separation of Concerns ○ Model-View-ControllerMuhammad Usman Chaudhry CS4615 SZABIST
  4. 4. Classes & Objects ● Coming code example will explain: ○ Classes ○ Objects ○ Encapsulation ○ Constructors ○ Class Members & Methods ○ Instance Members & Methods ○ Entry Point ○ Getter & SettersMuhammad Usman Chaudhry CS4615 SZABIST
  5. 5. //Student.javaclass 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. 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 CallMuhammad Usman Chaudhry CS4615 SZABIST
  7. 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. 8. Example: Static & Inner Nested Classes//Outer class can only be public or package-privateclass 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. 9. Example: Accessing Nested Inner Class//Accessing Nested Inner ClassOuterClass oc = new OuterClass(); //Either create new object or use previous instanceOuterClass.InnerClass innerClassObject = oc.new InnerClass(); //Way#1OuterClass.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. 10. Example: Accessing Nested Static Class//Accessing Nested Static ClassOuterClass.StaticNestedClass sncObj = new OuterClass.StaticNestedClass();● As simple as creating the normal object. No added syntax.Muhammad Usman Chaudhry CS4615 SZABIST
  11. 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 its declared.Muhammad Usman Chaudhry CS4615 SZABIST
  12. 12. Example: Local Inner Classclass OuterClass{ private int someVariable; public OuterClass(){ //Local inner classes dont 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. 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 codingMuhammad Usman Chaudhry CS4615 SZABIST
  14. 14. Why Use Nested Classes ● Logically grouping classes together. ● Increase encapsulation. ● Clean coding.Muhammad Usman Chaudhry CS4615 SZABIST
  15. 15. Important ● Java dont 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. 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. 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. 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. 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 superclasss 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. 20. //Class professional //Calling allclass 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 //programmers 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(){ //programmers 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. 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. 22. //Abstract class example //Implementationabstract 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. 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. 24. //Interface example //Implementationpublic 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. 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. 26. Packages ● Grouping similar classes together is called package. ● Its 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. 27. //Package example//Sample packagepackage net.thepaksoft.appname; //current package//all graphics related customized classesimport net.thepaksoft.appname.graphics.*;//ListView classimport net.thepaksoft.appname.controls.ListView;Muhammad Usman Chaudhry CS4615 SZABIST
  28. 28. Annotations & Javadocs ● Annotation provide data about code, they dont 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. 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. 30. Design Patterns ● Theyre 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. ● Well study the most relevant and commonly used under android.Muhammad Usman Chaudhry CS4615 SZABIST
  31. 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. 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. 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 ○ ResrouceCursorAdapterMuhammad Usman Chaudhry CS4615 SZABIST
  34. 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. 35. Separation of Concerns ● Appropriate layered approach ● Separate Presentation, Business Logic, from Design ● Partial classes, under Smalltalk, .Net & Ruby ● MVC, MVP, MVVM etc. PatternsMuhammad Usman Chaudhry CS4615 SZABIST
  36. 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. 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 dont have knowledge of Model. ○ Models have no knowledge of Views.Muhammad Usman Chaudhry CS4615 SZABIST
  38. 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. 39. Thats All for Today ● Have great vacations & Eid Mubarak!Muhammad Usman Chaudhry CS4615 SZABIST
  40. 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

×