Java Basics #3
Java Constructors
A constructor in Java is a special method that is used to initialise objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes.
int x; // Create a class attribute
// Create a class constructor for the Main class
public Main() {
}
public static void main(String[] args) {
Main myObj = new Main(); // Create an object of class Main (This will call the constructor)
System.out.println(myObj.x); // Print the value of x
}
// Outputs 5
Note that the constructor name must match the class name, and it cannot have a return type (like void
).
Also note that the constructor is called when the object is created.
All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you. However, then you are not able to set initial values for object attributes.
Constructor Parameters
Constructors can also take parameters, which is used to initialize attributes.
The following example adds an int y
parameter to the constructor. Inside the constructor we set x to y (x=y). When we call the constructor, we pass a parameter to the constructor (5), which will set the value of x to 5.
public class Main {
int x;
public Main(int y) {
x = y;
}
public static void main(String[] args) {
Main myObj = new Main(5);
System.out.println(myObj.x);
}
}
// Outputs 5
Parameters and Arguments
Information can be passed to methods as parameter. Parameters act as variables inside the method.
Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.
The following example has a method that takes a String
called fname as parameter. When the method is called, we pass along a first name, which is used inside the method to print the full name.
static void myMethod(String fname) {
System.out.println(fname + " Refsnes");
}
public static void main(String[] args) {
myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
}
}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
Multiple Parameters
You can have as many parameters as you like.
static void myMethod(String fname, int age) {
System.out.println(fname + " is " + age);
}
public static void main(String[] args) {
myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
}
}
// Liam is 5
// Jenny is 8
// Anja is 31
Return Values
The void
keyword, used in the examples above, indicates that the method should not return a value. If you want the method to return a value, you can use a primitive data type (such as int
, char
, etc.) instead of void
, and use the return
keyword inside the method.
static int myMethod(int x) {
return 5 + x;
}
public static void main(String[] args) {
System.out.println(myMethod(3));
}
}
// Outputs 8 (5 + 3)
Method Overloading
With method overloading, multiple methods can have the same name with different parameters.
float myMethod(float x)
double myMethod(double x, double y)
static int plusMethodInt(int x, int y) {
return x + y;
}
static double plusMethodDouble(double x, double y) {
return x + y;
}
public static void main(String[] args) {
int myNum1 = plusMethodInt(8, 5);
double myNum2 = plusMethodDouble(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
}
Instead of defining two methods that should do the same thing, it is better to overload one.
return x + y;
}
static double plusMethod(double x, double y) {
return x + y;
}
public static void main(String[] args) {
int myNum1 = plusMethod(8, 5);
double myNum2 = plusMethod(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
}
Java Scope
In Java, variables are only accessible inside the region they are created. This is called scope.
Method Scope
Variables declared directly inside a method are available anywhere in the method following the line of code in which they were declared.
Example:
public static void main(String[] args) {
// Code here CANNOT use x
int x = 100;
// Code here can use x
System.out.println(x);
}
}
Block Scope
A block of code refers to all of the code between curly braces {}
. Variables declared inside blocks of code are only accessible by the code between the curly braces, which follows the line in which the variable was declared.
Example:
public static void main(String[] args) {
// Code here CANNOT use x
{ // This is a block
// Code here CANNOT use x
int x = 100;
// Code here CAN use x
System.out.println(x);
} // The block ends here
// Code here CANNOT use x
}
}
Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve this, you must:
- declare class variables/attributes as
private
- provide public get and set methods to access and update the value of a
private
variable.
Get and Set
You learned from the previous chapter that private
variables can only be accessed within the same class (an outside class has no access to it). However, it is possible to access them if we provide public get and set methods.
The get
method returns the variable value, and the set
method sets the value.
Syntax for both is that they start with either get
or set
, followed by the name of the variable, with the first letter in upper case.
Example:
private String name; // private = restricted access
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}
public class Main {
public static void main(String[] args) {
Person myObj = new Person();
myObj.name = "John"; // error
System.out.println(myObj.name); // error
}
}
If the variable was declared as public
,
Then the output will be John.
However, as we try to access a private
variable, we get an error.
Instead, we use the getName()
and setName()
methods to acccess and update the variable.
Example:
public static void main(String[] args) {
Person myObj = new Person();
myObj.setName("John"); // Set the value of the name variable to "John"
System.out.println(myObj.getName());
}
}
// Outputs "John"
Why Encapsulation?
- Better control of class attributes and methods
- Class attributes can be made read-only (if you only use the
get
method), or write-only (if you only use theset
method) - Flexible: the programmer can change one part of the code without affecting other parts
- Increased security of data.
Comments
Post a Comment