Difference between revisions of "Android App"
Line 1: | Line 1: | ||
− | + | ==Methods== | |
− | + | Methods are nothing but members of a class that provide a service for an object or perform some business logic. | |
+ | |||
+ | ===Method Overloading=== | ||
+ | Overloading: Multiple methods with the same name but different parameter lists. | ||
+ | |||
+ | '''In constructors:''' | ||
+ | <syntaxhighlight lang="java"> | ||
+ | Item item1 = new Item(); | ||
+ | Item milk = new Item(“milk”, 0.99, 3); | ||
+ | |||
+ | String x = new String(); | ||
+ | String y = new String(“Hello”); | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | '''In methods:''' | ||
+ | <syntaxhighlight lang="java"> | ||
+ | String x = new String("Hola, cómo estás"); | ||
+ | x.substring(2); | ||
+ | x.substring(2, 5); | ||
+ | x.indexOf("h"); | ||
+ | x.indexOf("h", 1); | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | ===Standard Methods=== | ||
+ | Two methods that should be included in classes (Good practice to include it): | ||
+ | |||
+ | *toString | ||
+ | *equals | ||
+ | |||
+ | ====The toString Methodg==== | ||
+ | |||
+ | *'''Returns data stored in an object as a String:''' | ||
+ | **Allows the contents of an object to be displayed | ||
+ | **Can format the contents whatever way you wish | ||
+ | **MUST return a String* | ||
+ | **MUST NOT take a parameter* | ||
+ | |||
+ | <syntaxhighlight lang="java"> | ||
+ | public String toString() { | ||
+ | return name + ", " + day + " " + monthNames[month-1] + " " + year + ", " + address; | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | Example result: | ||
+ | |||
+ | <syntaxhighlight lang="bash"> | ||
+ | "P. Sherman, 30 May 2003, 42 Wallaby Way, Sydney" | ||
+ | </syntaxhighlight> |
Revision as of 22:26, 5 August 2019
Methods
Methods are nothing but members of a class that provide a service for an object or perform some business logic.
Method Overloading
Overloading: Multiple methods with the same name but different parameter lists.
In constructors:
Item item1 = new Item();
Item milk = new Item(“milk”, 0.99, 3);
String x = new String();
String y = new String(“Hello”);
In methods:
String x = new String("Hola, cómo estás");
x.substring(2);
x.substring(2, 5);
x.indexOf("h");
x.indexOf("h", 1);
Standard Methods
Two methods that should be included in classes (Good practice to include it):
- toString
- equals
The toString Methodg
- Returns data stored in an object as a String:
- Allows the contents of an object to be displayed
- Can format the contents whatever way you wish
- MUST return a String*
- MUST NOT take a parameter*
public String toString() {
return name + ", " + day + " " + monthNames[month-1] + " " + year + ", " + address;
}
Example result:
"P. Sherman, 30 May 2003, 42 Wallaby Way, Sydney"