Advertisement
yo2man

Some more notes on Java and OOP Concepts

Jul 17th, 2015
265
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 17.45 KB | None | 0 0
  1. Some more notes on Java and Object Oriented Programming Concepts.(Unrelated to Treehouse course)
  2. // https://www.youtube.com/watch?v=lbXsrHGhBAU
  3. /*
  4.  
  5.  
  6. // Getters and Setters methods: http://pastebin.com/Jpiimu19
  7.  
  8.  
  9. object.method(args)
  10.  
  11. class member:
  12. class.field                                 aka static field
  13. class.method(args)                               static method
  14.  
  15. Unlike in python where global variables/plain functions can live outside the class, Java forces everything to live inside classes, thus the only way to use these one-off variables is to put them in a class.
  16.  
  17. Just remember these are not true members of a class in a proper Object Oriented sense. Simple.
  18.  
  19. Constructor is simply a method that is run when we instantiate a class.
  20.  
  21.  
  22. Interface is a set of method.
  23. Two different classes though unrelated, can share a set of methods. We call those set of methods: interfaces. Simple.
  24.  
  25. Abstract class is a class that is not meant to be instantiated. Instead an abstract class is just meant to serve as an ancestor to other classes. For example in your code you may have no need for a mammal object but you need a dog and cat object so you create an abstract class: mammal, from which you extend the dog and cat classes.
  26. */
  27.  
  28.  
  29.  
  30. //----------------------------------------------------------------
  31. submitOrder(...) {
  32.     blah blah blah
  33.     blah blah blah                                                                   calculatePrice(...){
  34.     calculatePrice(...)     input parameters (in this case Quantity of Coffee)----->          blah blah blah
  35.          blah blah blah             <----output parameters (Total Price)*                        }
  36. }
  37.  
  38. ie: input Quantity of coffee---> caculatePrice() calculates price ------> get output* Total Price    ....which we than use in the SubmitOrder()
  39.  
  40.  
  41. // https://www.udacity.com/course/viewer#!/c-ud837/l-4619208555/e-4593449017/m-4593449018
  42.  
  43. // This is a method signature
  44. private int calculatePrice(int quantity, int priceOfOneCup) {
  45. }
  46.  
  47. AccessModifier ReturnAkaOutputDataType MethodName(input_Parameter-1-dataType input_Parameter-1-variableNameWeGiveIt) {
  48.     return "Welcome to San Francisco where the temperature is " + input_Parameter-1-variableNameWeGiveIt + "Celsius" ; <--output
  49. }
  50. // Access Modifier determines who has access to this method. Ie: public, private or protected.
  51. // Return data type is the type of data that is returned in the output* (ie: int)
  52.  
  53. methodname(input1, input2) { <- input parameters have to be in order
  54. }
  55.  
  56. //Method name usually and should began with a verb. Ie:
  57. /*runProgram
  58. setProgram
  59. isId
  60. calculatePrice */
  61.  
  62. // Args = arguments = inputs passed to a method
  63. // pretty much input parameter and arguments are used interchangeably in the workplace.
  64. // but here is an example anyway:
  65. /* public void MyMethod(parameter){
  66.     string myArg1 = "this is my argument";
  67.     myClass.MyMethod(myArg!)
  68.     }
  69.  
  70. parameter == when we define the function , argument == when we call to that method
  71. */
  72.  
  73.  
  74.  
  75. //-----------------
  76. // It doesn't matter to the caller of the method what the input parameter's name is.
  77.  
  78.     public void increment(View view) {
  79.             quantity = quantity + 1; //*
  80.         displayQuantity(quantity);
  81.         displayPrice(quantity * 5); //<-- calls the displayQuantity() and inputs in the Quantity variable *from above.
  82.     }
  83.  
  84.     private void displayQuantity(int numberOfCoffees) {//<- it doesn't matter that the variable name for input is "numberOfCoffees", as long as the input value is a matching datatype (in this case: 'int'), it works. Simple.
  85.         TextView quantityTextView = (TextView) findViewById(
  86.                 R.id.quantity_text_view);
  87.         quantityTextView.setText("" + numberOfCoffees);
  88.     }
  89.  
  90. //-------------------------------------------------------------------------------
  91. //Multiple parameters:
  92. public class MainActivty extends AppCompatActivity {
  93.     @Override
  94.     protected void onCreate (Bundle savedInstanceState){
  95.     super.OnCreate9savedInstanceState);
  96.     setContentView(R.layout.activity_main);
  97.     createWeatherMessage(77, "San Francisco"); //[param pass in to the one below]
  98. }
  99.  
  100.  
  101. private String createWeatherMessage(int temperature, String cityName){ //[param]
  102.     return "Welcome to " + cityName + " where the temperature is " + temperature + "Celsius";
  103. }
  104.  
  105. //Result: "Welcome to San Francisco where the temperature is 77 Celsius"
  106.  
  107. // https://www.udacity.com/course/viewer#!/c-ud837/l-4619208555/e-4593449026/m-4593449027
  108.  
  109.  
  110. //Psuedo code
  111. in submitOrder method:
  112.     int price* = calculatePrice();  <--- the way you think is more like this:     calculatePrice() = int price;
  113.     display(price*)                                                                          display(price);
  114.  
  115.  
  116.  
  117. //Variable Scopes:
  118.  
  119. public void method(){
  120.     int price = blahblah();   //not the same as the one below
  121. }
  122.  
  123. private int calculatePrice(){
  124.     int price = quantity *5; //not the same as the one above
  125.     return price;
  126. }
  127.  
  128. /*
  129. You can give two different variables the same name (ie: "price") but because they are in different variable scopes so its okay.
  130. They are independent from each other. The way Java works, once java finishes executing the first method and the price, the price variable is gone. It then goes on to execute the second method and create a second price variable then delete it. Simple.
  131. // https://www.udacity.com/course/viewer#!/c-ud837/l-4619208555/e-4593449032/m-4593449034
  132. */
  133.  
  134. //--------------------------------------------------------------------------------
  135.  
  136. //Why use Getters and Setters?
  137. //So you don't have to change every value you had set (ex: in the future you want to change "int age = 103" to "int age =< 100").
  138. // to access stuff that you have Encapsulated(private)
  139. and some more reasons: http://stackoverflow.com/questions/1568091/why-use-getters-and-setters
  140.  
  141.  
  142. // Getters and Setters
  143.  
  144. public void setText(String text) { //The setText method takes an input (in this case, a String)
  145.     mText = text;                //and then it updates the global variable mText to = this new value.
  146. }
  147.  
  148. public void setTextColor(int color) { //
  149.     mTextColor = color;
  150. }
  151. //--------------------------
  152.  
  153. //What is a Constructor
  154. /* A constructor in Java is a block of code similar to a method that’s called when an instance of an object is created. Here are the key differences between a constructor and a method:
  155. 1. A constructor doesn’t have a return type.
  156. 2. The name of the constructor must be the same as the name of the class.
  157. 3. Unlike methods, constructors are not considered members of a class.
  158. 4. A constructor is called automatically when a new instance of an object is created.
  159. Here’s the basic format for coding a constructor:
  160. */
  161. public ClassName (parameter-list) [throws exception...]
  162. {
  163.     statements...
  164. }
  165. // The public keyword indicates that other classes can access the constructor. ClassName must be the same as the name of the class that contains the constructor. You code the parameter list the same way that you code it for a method.
  166. //explanation: constructor for dummies: http://www.dummies.com/how-to/content/how-to-use-a-constructor-in-java.html
  167.  
  168.  
  169. //-----------------------------------------------------
  170.  
  171. // Generics<WhatAreThey?>
  172. //Generic class is a type of class that can work with other objects.
  173. //you specify what type of object it can work with when create objects from the class.
  174.  
  175. //Generics for dummies explanation: http://www.dummies.com/how-to/content/create-a-generic-class-in-java.html
  176.  
  177. //-------------------------------------------------------
  178. private Context mContext;
  179.  
  180. //What is Context?
  181. // its the context of current state of the application/object. It lets newly created objects understand what has been going on.
  182. // it is like a remote control that gets you the tv channels on the TV (except replace channels with Resources).
  183.  
  184. //You can get the context by invoking 'getApplicationContext()', 'getContext()', 'getBaseContext()' or 'this' (when in the activity class).
  185. //http://stackoverflow.com/questions/3572463/what-is-context-in-android
  186.  
  187. //----------------
  188. Member variable is just another way to say field or the state of the class.
  189.  
  190. //--------------
  191.  
  192. Simplified ImageView class (ImageView.java)
  193.  
  194. /**
  195.  * Displays an image, such as an icon.
  196.  */
  197. public class ImageView extends View {
  198.  
  199.     private int mImageId; // Resource ID for the source image that should be displayed in the ImageView.
  200.  
  201.     private Context mContext; // Context of the app
  202.  
  203.     /**
  204.      * Constructor: constructs a new ImageView.
  205.      */
  206.     public ImageView(Context context) { // it takes the input 'Context context' and constructs an ImageView object
  207.         mImageId = 0;
  208.         mContext = context;
  209.     }
  210.  
  211.     /**
  212.      * Sets the source image in the ImageView.
  213.      *
  214.      * @param imageId is the resource ID of the image to be displayed.
  215.      */
  216.     public void setImage(int imageId) {
  217.         mImageId = imageId;
  218.     }
  219. }
  220.  
  221. //-----------------------------------------------
  222. //Creating an Object
  223.  
  224.  
  225. // https://www.udacity.com/course/viewer#!/c-ud837/l-4619208555/e-4578145062/m-4593449044
  226.  
  227. //-----------------------------------------------
  228. Udacity
  229.  
  230. // Practice calling Method on Object
  231. //since we are calling a method ON an object, we use the dot syntax: '.'
  232. //ie: orderSummaryTextView.setText(message);
  233.  
  234. public class MainActivity extends ActionBarActivity {
  235.  
  236.     @Override
  237.     protected void onCreate(Bundle savedInstanceState) {
  238.         super.onCreate(savedInstanceState);
  239.  
  240.         //Screen should show "Wow" in GREEN and size: 56 instead of the original "Hello World"
  241.  
  242.         TextView textView = new TextView(this); // 'this' refers to this activity we are in
  243.         textView.setText("Wow! lalalalalalalallalalalalallalalalalalallalalala");
  244.         textView.setTextSize(56);
  245.         textView.setTextColor(Color.GREEN);
  246.         textView.setMaxLines(2);
  247.  
  248.  
  249.         setContentView(textView); //pass in textView variable //normally we pass in the Resource Id into 'setContentView' because normally the layout is more complex and require building in XML
  250.     }
  251.  
  252. // https://www.udacity.com/course/viewer#!/c-ud837/l-4619208555/e-4579808103/m-4593449046
  253.  
  254.  
  255. //----------------------------------------
  256. //Inheritance Override
  257.  
  258. public class MainActivity extends ActionBarActivity {
  259.  
  260.  
  261.     @Override
  262.     protected void onCreate(Bundle savedInstanceState) { //this Overrides the ActionBarActivity and gets the XML file in this case: Hello World
  263.         super.onCreate(savedInstanceState);
  264.         setContentView(R.layout.activity_main);
  265.     }
  266.  
  267.  
  268.     @Override
  269.     public boolean onCreateOptionsMenu(Menu menu) {  //This Overrides the ActionBarActivity and creates the three dots [...] menu on the action bar
  270.         // Inflate the menu; this adds items to the action bar if it is present.
  271.         getMenuInflater().inflate(R.menu.menu_main, menu);
  272.         return true;
  273.     }
  274.  
  275. // https://www.udacity.com/course/viewer#!/c-ud837/l-4619208555/e-4578104913/m-4601468623
  276.  
  277. //-----------------------------
  278. // Sample Code from findViewById lessons in Udacity Android For Beginners Course:
  279. //you should be able to read and understand these:
  280.  
  281.         TextView nameTextView = (TextView) findViewById(R.id.name);
  282.         nameTextView.setText("Laura");
  283.  
  284.         TextView description = (TextView) findViewById(R.id.description);
  285.         int getMaxLines = description.getMaxLines();
  286.  
  287.         ImageView iconImageView = (ImageView) findViewById(R.id.icon);
  288.         iconImageView.setImageResource(R.drawable.logo);
  289.  
  290.         View textView = findViewById(R.id.title);
  291.         textView.setVisibility(View.GONE);
  292.  
  293.  
  294. // https://www.udacity.com/course/viewer#!/c-ud837/l-4619208555/e-4583694859/m-4607898804
  295.  
  296. //------------------------------------------------------------------
  297. Lesson 3B
  298. //------------------------------------------------------------------
  299. //Check boxes, detect if checkbox is checked:
  300.    
  301.     //this method is called when the order button is clicked:
  302.      public void submitOrder(View view) {
  303.     //....other methods and variables that distract from the lesson removed....
  304.         // Figure out if the user wants whipped cream topping
  305.         CheckBox whippedCreamCheckBox = (CheckBox) findViewById(R.id.whipped_cream_checkbox); //id links to checkbox xml
  306.         boolean hasWhippedCream = whippedCreamCheckBox.isChecked();  //isChecked() is a default method
  307.     Log.v("MainActivity", "Has whipped cream: " + hasWhippedCream);  // we concatenated 'hasWhippedCream' to it --> so it will show "Has whipped cream: true" or "Has whipped cream: false"
  308.     //Log.v( "String" [aka TAG], "String" [aka the description of what we are testing] );
  309. //simple.
  310.  
  311.     int price = calculatePrice();
  312.     // add in the extra input parameter for hasWhippedCream boolean
  313.     String priceMessage = createOrderSummary(price, hasWhippedCream);
  314.     displayMessage(priceMessage);
  315. }
  316.  
  317. //Create the summary of the order
  318. // add the extra input parameter in order to input the boolean hasWhippedCream
  319. private String createOrderSummary(int price, boolean nameThatDoesNotNecessarilyHaveToMatchHasWhippedCream) {
  320.     String priceMessage = "Name: Lyla";
  321.     priceMessage += "\n Total: $ " + price;
  322.     priceMessage += "\n Does it have whipped cream: " + nameThatDoesNotNecessarilyHaveToMatchHasWhippedCream;
  323.     return priceMessage;
  324. }
  325. //------------------------------------------------------------------
  326. //Implementing editText, similar to checkbox
  327.  
  328.      public void submitOrder(View view) {
  329.     //....other methods and variables that distract from the lesson removed....
  330.         CheckBox whippedCreamCheckBox = (CheckBox) findViewById(R.id.whipped_cream_checkbox);
  331.         boolean hasWhippedCream = whippedCreamCheckBox.isChecked();
  332.  
  333.     EditText nameField = (EditText) findViewById(R.id.name_field);
  334.     String name = nameField.getText().toString(); //chaining method calls. the reason we use this is because '.getText()' method returns an 'Editable' object so we need '.toString()' to convert it to a 'String' which can then be stored '= String name'.
  335.     Log.v("MainActivity", "Name: " + name);
  336.  
  337. //simple.
  338.  
  339.     int price = calculatePrice();
  340.     // add in the extra input parameter for name
  341.     String priceMessage = createOrderSummary(name, price, hasWhippedCream);
  342.     displayMessage(priceMessage);
  343. }
  344. //Create the summary of the order
  345. // add the extra input parameter in order to input the String name
  346. private String createOrderSummary(String name, int price, boolean nameThatDoesNotNecessarilyHaveToMatchHasWhippedCream) {
  347.     String priceMessage = "Name: " + name;
  348.     priceMessage += "\n Total: $ " + price;
  349.     priceMessage += "\n Does it have whipped cream: " + nameThatDoesNotNecessarilyHaveToMatchHasWhippedCream;
  350.     return priceMessage;
  351.  
  352. //------------------------------------------------------------------
  353. //Protip: stuck on how to implement something like chat messaging or EditText return inputted name? look at clean open source apps and copy from them.
  354. //------------------------------------------------------------------
  355.  
  356. more on if else:
  357.  
  358. int numberOfEmailsInInbox = 0;
  359. int numberOfDraftEmails = 2;
  360. String emailMessage = "You have " + numberOfEmailsInInbox + " emails. ";
  361. String draftMessage = "You have " + numberOfDraftEmails + " email drafts.";
  362. if (numberOfEmailsInInbox == 0) {
  363.     emailMessage = "You have no new messages. "; //this would replace/update the previous 'emailMessage' if (condition) is true.
  364. }
  365.  
  366.  
  367. if (numberOfDraftEmails == 0) {
  368.     draftMessage = "You have no new drafts.";
  369. }
  370.  
  371.  
  372. Log.v("InboxActivity", emailMessage);
  373. Log.v("InboxActivity", draftMessage);
  374.  
  375. //Result:
  376. // V/InboxActivity: You have no new messages.
  377. // V/InboxActivity: You have 2 email drafts.
  378.  
  379. // Simple.
  380.  
  381. //----------------------------------------------------
  382. // Chaining Statements, the else/if
  383.  
  384. //Consider the following scenario about weekend plans among friends. These friends happen to be picky and what they do when hanging out:
  385.  
  386. /*
  387. If you want to go sing karaoke, then Lyla and Larry will come along. Otherwise if you want to go to a football game, only Lyla will go. Otherwise everyone will stay home.
  388. */
  389.  
  390. boolean goingToKaraoke = false;
  391. boolean goingToFootballGame = true;
  392.  
  393. if (goingToKaraoke) {
  394.    Log.v("WeekendActivity", "Lyla and Larry will join in.");
  395. } else if (goingToFootballGame) {
  396.    Log.v("WeekendActivity", "Just Lyla will come.");          
  397. } else {
  398.    Log.v("WeekendActivity", "Nobody is interested in coming :( ");  
  399. }
  400.  
  401. //Callbacks:
  402.  
  403.  
  404.  
  405. // >   How to explain callbacks in plain English?
  406.  
  407. // In plain English, a callback function is like a Worker who "calls back" to his Manager when he has completed a Task.
  408.  
  409. // >    How are they different from calling one function from another function taking some context from the calling function?
  410.  
  411. // It is true that you are calling a function from another function, but the key is that the callback is treated like an Object, so you can change which Function to call based on the state of the system (like the Strategy Design Pattern).
  412.  
  413. // >    How can their power be explained to a novice programmer?
  414.  
  415. // The power of callbacks can easily be seen in AJAX-style websites which need to pull data from a server. Downloading the new data may take some time. Without callbacks, your entire User Interface would "freeze up" while downloading the new data, or you would need to refresh the entire page rather than just part of it. With a callback, you can insert a "now loading" image and replace it with the new data once it is loaded.
  416.  
  417. More explanations:
  418. // http://www.quora.com/How-to-explain-callbacks-in-plain-English-How-are-they-different-from-calling-one-function-from-another-function
  419.  
  420.  
  421. //simple.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement