Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Some more notes on Java and Object Oriented Programming Concepts.(Unrelated to Treehouse course)
- // https://www.youtube.com/watch?v=lbXsrHGhBAU
- /*
- // Getters and Setters methods: http://pastebin.com/Jpiimu19
- object.method(args)
- class member:
- class.field aka static field
- class.method(args) static method
- 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.
- Just remember these are not true members of a class in a proper Object Oriented sense. Simple.
- Constructor is simply a method that is run when we instantiate a class.
- Interface is a set of method.
- Two different classes though unrelated, can share a set of methods. We call those set of methods: interfaces. Simple.
- 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.
- */
- //----------------------------------------------------------------
- submitOrder(...) {
- blah blah blah
- blah blah blah calculatePrice(...){
- calculatePrice(...) input parameters (in this case Quantity of Coffee)-----> blah blah blah
- blah blah blah <----output parameters (Total Price)* }
- }
- ie: input Quantity of coffee---> caculatePrice() calculates price ------> get output* Total Price ....which we than use in the SubmitOrder()
- // https://www.udacity.com/course/viewer#!/c-ud837/l-4619208555/e-4593449017/m-4593449018
- // This is a method signature
- private int calculatePrice(int quantity, int priceOfOneCup) {
- }
- AccessModifier ReturnAkaOutputDataType MethodName(input_Parameter-1-dataType input_Parameter-1-variableNameWeGiveIt) {
- return "Welcome to San Francisco where the temperature is " + input_Parameter-1-variableNameWeGiveIt + "Celsius" ; <--output
- }
- // Access Modifier determines who has access to this method. Ie: public, private or protected.
- // Return data type is the type of data that is returned in the output* (ie: int)
- methodname(input1, input2) { <- input parameters have to be in order
- }
- //Method name usually and should began with a verb. Ie:
- /*runProgram
- setProgram
- isId
- calculatePrice */
- // Args = arguments = inputs passed to a method
- // pretty much input parameter and arguments are used interchangeably in the workplace.
- // but here is an example anyway:
- /* public void MyMethod(parameter){
- string myArg1 = "this is my argument";
- myClass.MyMethod(myArg!)
- }
- parameter == when we define the function , argument == when we call to that method
- */
- //-----------------
- // It doesn't matter to the caller of the method what the input parameter's name is.
- public void increment(View view) {
- quantity = quantity + 1; //*
- displayQuantity(quantity);
- displayPrice(quantity * 5); //<-- calls the displayQuantity() and inputs in the Quantity variable *from above.
- }
- 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.
- TextView quantityTextView = (TextView) findViewById(
- R.id.quantity_text_view);
- quantityTextView.setText("" + numberOfCoffees);
- }
- //-------------------------------------------------------------------------------
- //Multiple parameters:
- public class MainActivty extends AppCompatActivity {
- @Override
- protected void onCreate (Bundle savedInstanceState){
- super.OnCreate9savedInstanceState);
- setContentView(R.layout.activity_main);
- createWeatherMessage(77, "San Francisco"); //[param pass in to the one below]
- }
- private String createWeatherMessage(int temperature, String cityName){ //[param]
- return "Welcome to " + cityName + " where the temperature is " + temperature + "Celsius";
- }
- //Result: "Welcome to San Francisco where the temperature is 77 Celsius"
- // https://www.udacity.com/course/viewer#!/c-ud837/l-4619208555/e-4593449026/m-4593449027
- //Psuedo code
- in submitOrder method:
- int price* = calculatePrice(); <--- the way you think is more like this: calculatePrice() = int price;
- display(price*) display(price);
- //Variable Scopes:
- public void method(){
- int price = blahblah(); //not the same as the one below
- }
- private int calculatePrice(){
- int price = quantity *5; //not the same as the one above
- return price;
- }
- /*
- You can give two different variables the same name (ie: "price") but because they are in different variable scopes so its okay.
- 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.
- // https://www.udacity.com/course/viewer#!/c-ud837/l-4619208555/e-4593449032/m-4593449034
- */
- //--------------------------------------------------------------------------------
- //Why use Getters and Setters?
- //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").
- // to access stuff that you have Encapsulated(private)
- and some more reasons: http://stackoverflow.com/questions/1568091/why-use-getters-and-setters
- // Getters and Setters
- public void setText(String text) { //The setText method takes an input (in this case, a String)
- mText = text; //and then it updates the global variable mText to = this new value.
- }
- public void setTextColor(int color) { //
- mTextColor = color;
- }
- //--------------------------
- //What is a Constructor
- /* 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:
- 1. A constructor doesn’t have a return type.
- 2. The name of the constructor must be the same as the name of the class.
- 3. Unlike methods, constructors are not considered members of a class.
- 4. A constructor is called automatically when a new instance of an object is created.
- Here’s the basic format for coding a constructor:
- */
- public ClassName (parameter-list) [throws exception...]
- {
- statements...
- }
- // 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.
- //explanation: constructor for dummies: http://www.dummies.com/how-to/content/how-to-use-a-constructor-in-java.html
- //-----------------------------------------------------
- // Generics<WhatAreThey?>
- //Generic class is a type of class that can work with other objects.
- //you specify what type of object it can work with when create objects from the class.
- //Generics for dummies explanation: http://www.dummies.com/how-to/content/create-a-generic-class-in-java.html
- //-------------------------------------------------------
- private Context mContext;
- //What is Context?
- // its the context of current state of the application/object. It lets newly created objects understand what has been going on.
- // it is like a remote control that gets you the tv channels on the TV (except replace channels with Resources).
- //You can get the context by invoking 'getApplicationContext()', 'getContext()', 'getBaseContext()' or 'this' (when in the activity class).
- //http://stackoverflow.com/questions/3572463/what-is-context-in-android
- //----------------
- Member variable is just another way to say field or the state of the class.
- //--------------
- Simplified ImageView class (ImageView.java)
- /**
- * Displays an image, such as an icon.
- */
- public class ImageView extends View {
- private int mImageId; // Resource ID for the source image that should be displayed in the ImageView.
- private Context mContext; // Context of the app
- /**
- * Constructor: constructs a new ImageView.
- */
- public ImageView(Context context) { // it takes the input 'Context context' and constructs an ImageView object
- mImageId = 0;
- mContext = context;
- }
- /**
- * Sets the source image in the ImageView.
- *
- * @param imageId is the resource ID of the image to be displayed.
- */
- public void setImage(int imageId) {
- mImageId = imageId;
- }
- }
- //-----------------------------------------------
- //Creating an Object
- // https://www.udacity.com/course/viewer#!/c-ud837/l-4619208555/e-4578145062/m-4593449044
- //-----------------------------------------------
- Udacity
- // Practice calling Method on Object
- //since we are calling a method ON an object, we use the dot syntax: '.'
- //ie: orderSummaryTextView.setText(message);
- public class MainActivity extends ActionBarActivity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- //Screen should show "Wow" in GREEN and size: 56 instead of the original "Hello World"
- TextView textView = new TextView(this); // 'this' refers to this activity we are in
- textView.setText("Wow! lalalalalalalallalalalalallalalalalalallalalala");
- textView.setTextSize(56);
- textView.setTextColor(Color.GREEN);
- textView.setMaxLines(2);
- 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
- }
- // https://www.udacity.com/course/viewer#!/c-ud837/l-4619208555/e-4579808103/m-4593449046
- //----------------------------------------
- //Inheritance Override
- public class MainActivity extends ActionBarActivity {
- @Override
- protected void onCreate(Bundle savedInstanceState) { //this Overrides the ActionBarActivity and gets the XML file in this case: Hello World
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) { //This Overrides the ActionBarActivity and creates the three dots [...] menu on the action bar
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.menu_main, menu);
- return true;
- }
- // https://www.udacity.com/course/viewer#!/c-ud837/l-4619208555/e-4578104913/m-4601468623
- //-----------------------------
- // Sample Code from findViewById lessons in Udacity Android For Beginners Course:
- //you should be able to read and understand these:
- TextView nameTextView = (TextView) findViewById(R.id.name);
- nameTextView.setText("Laura");
- TextView description = (TextView) findViewById(R.id.description);
- int getMaxLines = description.getMaxLines();
- ImageView iconImageView = (ImageView) findViewById(R.id.icon);
- iconImageView.setImageResource(R.drawable.logo);
- View textView = findViewById(R.id.title);
- textView.setVisibility(View.GONE);
- // https://www.udacity.com/course/viewer#!/c-ud837/l-4619208555/e-4583694859/m-4607898804
- //------------------------------------------------------------------
- Lesson 3B
- //------------------------------------------------------------------
- //Check boxes, detect if checkbox is checked:
- //this method is called when the order button is clicked:
- public void submitOrder(View view) {
- //....other methods and variables that distract from the lesson removed....
- // Figure out if the user wants whipped cream topping
- CheckBox whippedCreamCheckBox = (CheckBox) findViewById(R.id.whipped_cream_checkbox); //id links to checkbox xml
- boolean hasWhippedCream = whippedCreamCheckBox.isChecked(); //isChecked() is a default method
- 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"
- //Log.v( "String" [aka TAG], "String" [aka the description of what we are testing] );
- //simple.
- int price = calculatePrice();
- // add in the extra input parameter for hasWhippedCream boolean
- String priceMessage = createOrderSummary(price, hasWhippedCream);
- displayMessage(priceMessage);
- }
- //Create the summary of the order
- // add the extra input parameter in order to input the boolean hasWhippedCream
- private String createOrderSummary(int price, boolean nameThatDoesNotNecessarilyHaveToMatchHasWhippedCream) {
- String priceMessage = "Name: Lyla";
- priceMessage += "\n Total: $ " + price;
- priceMessage += "\n Does it have whipped cream: " + nameThatDoesNotNecessarilyHaveToMatchHasWhippedCream;
- return priceMessage;
- }
- //------------------------------------------------------------------
- //Implementing editText, similar to checkbox
- public void submitOrder(View view) {
- //....other methods and variables that distract from the lesson removed....
- CheckBox whippedCreamCheckBox = (CheckBox) findViewById(R.id.whipped_cream_checkbox);
- boolean hasWhippedCream = whippedCreamCheckBox.isChecked();
- EditText nameField = (EditText) findViewById(R.id.name_field);
- 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'.
- Log.v("MainActivity", "Name: " + name);
- //simple.
- int price = calculatePrice();
- // add in the extra input parameter for name
- String priceMessage = createOrderSummary(name, price, hasWhippedCream);
- displayMessage(priceMessage);
- }
- //Create the summary of the order
- // add the extra input parameter in order to input the String name
- private String createOrderSummary(String name, int price, boolean nameThatDoesNotNecessarilyHaveToMatchHasWhippedCream) {
- String priceMessage = "Name: " + name;
- priceMessage += "\n Total: $ " + price;
- priceMessage += "\n Does it have whipped cream: " + nameThatDoesNotNecessarilyHaveToMatchHasWhippedCream;
- return priceMessage;
- //------------------------------------------------------------------
- //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.
- //------------------------------------------------------------------
- more on if else:
- int numberOfEmailsInInbox = 0;
- int numberOfDraftEmails = 2;
- String emailMessage = "You have " + numberOfEmailsInInbox + " emails. ";
- String draftMessage = "You have " + numberOfDraftEmails + " email drafts.";
- if (numberOfEmailsInInbox == 0) {
- emailMessage = "You have no new messages. "; //this would replace/update the previous 'emailMessage' if (condition) is true.
- }
- if (numberOfDraftEmails == 0) {
- draftMessage = "You have no new drafts.";
- }
- Log.v("InboxActivity", emailMessage);
- Log.v("InboxActivity", draftMessage);
- //Result:
- // V/InboxActivity: You have no new messages.
- // V/InboxActivity: You have 2 email drafts.
- // Simple.
- //----------------------------------------------------
- // Chaining Statements, the else/if
- //Consider the following scenario about weekend plans among friends. These friends happen to be picky and what they do when hanging out:
- /*
- 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.
- */
- boolean goingToKaraoke = false;
- boolean goingToFootballGame = true;
- if (goingToKaraoke) {
- Log.v("WeekendActivity", "Lyla and Larry will join in.");
- } else if (goingToFootballGame) {
- Log.v("WeekendActivity", "Just Lyla will come.");
- } else {
- Log.v("WeekendActivity", "Nobody is interested in coming :( ");
- }
- //Callbacks:
- // > How to explain callbacks in plain English?
- // In plain English, a callback function is like a Worker who "calls back" to his Manager when he has completed a Task.
- // > How are they different from calling one function from another function taking some context from the calling function?
- // 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).
- // > How can their power be explained to a novice programmer?
- // 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.
- More explanations:
- // http://www.quora.com/How-to-explain-callbacks-in-plain-English-How-are-they-different-from-calling-one-function-from-another-function
- //simple.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement