4. Some Techniques in Class Building
4. Some Techniques in Class Building
Method signature
Method overloading
Methods in class can have the same name, if they have different signatures
(different number of arguments or different types of arguments)
Advantages
easier for devs since they don't have to remember too many method names.
Only apply this technique on methods describing the same kind of task
this keyword
Refer to the current obj, used inside the class of the obj that it refers to.
use attributes or methods of object through . operator
Example
Attribute/method that can not change its values/content during the usage.
Class members
Members belong to:
The whole class (static)
Individual (instance variables and methods)
Java Modifiers
Changing a value in one obj changes the val for all of the objs
Caution
Static methods can access only staic attributes and can call static methods
in the same class.
Variable Arguments
An arbitrary number of arguments, called varargs (nói đơn giản là cho nhập
số lượng ko giới hạn các @param có chung dạng dữ liệu)
Read more about Java Varargs
<Data_type>...<param_name>
sum();// return 0
sum(1,2)//return 3
sum(1, 2, 3, 4, 5) //return 15
Caution
Passing by values
Info
Pass the references by value, not the original reference or the object
But what if we want to swap two Object ?
// Class 1
// A car with model and no.
class Car {
// Attributes associated with car
int model, no;
// Constructor of class 1
Car(int model, int no)
{
// This refers to current instance itself
this.model = model;
this.no = no;
}
// Method
// To print object details
void print()
{
System.out.println("no = " + no
+ ", model = " + model);
}
}
// Class 2
// Wrapper over class that is used for swapping
class CarWrapper {
Car c;
// Constructor
CarWrapper(Car c) { this.c = c; }
}
// Class 3
// Uses Car class and swaps objects of Car
// using CarWrapper
class GFG {
// This method swaps car objects in wrappers
// cw1 and cw2
public static void swap(CarWrapper cw1, CarWrapper cw2)
{
Car temp = cw1.c;
cw1.c = cw2.c;
cw2.c = temp;
}