Pbo Java 1 Catatan (NOTE)
Pbo Java 1 Catatan (NOTE)
CATATAN
(NOTE)
Methods
Methods define behavior. A method is a collection of statements that are grouped together to perform an operation. System.out.println() is an
example of a method.
You can define your own methods to perform your desired tasks.
Let's consider the following code:
class MyClass {
The code above declares a method called "sayHello", which prints a text, and then gets called in main.
To call a method, type its name and then follow the name with a set of parentheses.
Calling Methods
class MyClass {
// Hello World!
// Hello World!
// Hello World!
In cases like the one above, where the same thing is repeated over and over, you can achieve the same result using loops (while or for).
Method Parameters
You can also create a method that takes some data, called parameters, along with it when you call it. Write parameters within the method's
parentheses.
For example, we can modify our sayHello() method to take and output a String parameter.
class MyClass {
}
// Hello David
// Hello Amy
The method above takes a String called name as a parameter, which is used in the method's body. Then, when calling the method, we pass the
parameter's value inside the parentheses.
Methods can take multiple, comma-separated parameters.
The advantages of using methods instead of simple statements include the following:
- code reuse: You can write a method once, and use it multiple times, without having to rewrite the code each time.
- parameters: Based on the parameters passed in, methods can perform various actions.
class MyClass {
Take a look at the same code from our previous lesson with explaining comments, so you can better understand how it works:// returns an int
value 5
static int returnFive() {
return 5;
}
// has a parameter
static void sayHelloTo(String name) {
System.out.println("Hello " + name);
}
A method can have one type of parameter (or parameters) and return another, different type. For example, it can take two doubles and return
an int.
Creating Classes
In order to create your own custom objects, you must first create the corresponding classes. This is accomplished by right clicking on
the src folder in Eclipse and selecting Create->New->Class.
Creating Objects
Let's head over to our main and create a new object of our class.
MyClass.java
class MyClass {
public static void main(String[ ] args) {
Animal dog = new Animal();
dog.bark();
}
}
// Outputs "Woof-Woof"Try It Yourself
Now, dog is an object of type Animal. Thus we can call its bark() method, using the name of the object and a dot.
The dot notation is used to access the object's attributes and methods.
You have just created your first object!
Defining Attributes
A class has attributes and methods. The attributes are basically variables within a class.
Let's create a class called Vehicle, with its corresponding attributes and methods.public class Vehicle {
int maxSpeed;
int wheels;
String color;
double fuelCapacity;
void horn() {
System.out.println("Beep!");
}
}
maxSpeed, wheels, color, and fuelCapacity are the attributes of our Vehicle class, and horn() is the only method.
You can define as many attributes and methods as necessary.
Creating Objects
Next, we can create multiple objects of our Vehicle class, and use the dot syntax to access their attributes and methods.
class MyClass {
public static void main(String[ ] args) {
Vehicle v1 = new Vehicle();
Vehicle v2 = new Vehicle();
v1.color = "red";
v2.horn();
}
}Try It Yourself
Access Modifiers
Now let's discuss the public keyword in front of the main method.public static void main(String[ ] args)
public is an access modifier, meaning that it is used to set the level of access. You can use access modifiers for classes, attributes, and methods.
For classes, the available modifiers are public or default (left blank), as described below:
public: The class is accessible by any other class.
default: The class is accessible only by classes in the same package.
Getters and Setters are used to effectively protect your data, particularly when creating classes. For each variable, the get method returns its
value, while the set method sets the value.
Getters start with get, followed by the variable name, with the first letter of the variable name capitalized.
Setters start with set, followed by the variable name, with the first letter of the variable name capitalized.
// Getter
public String getColor() {
return color;
}
// Setter
public void setColor(String c) {
this.color = c;
}
}
The getter method returns the value of the attribute.
The setter method takes a parameter and assigns it to the attribute.
The keyword this is used to refer to the current object. Basically, this.color is the color attribute of the current object.
Once our getter and setter have been defined, we can use it in our main:
Getters and setters allow us to have control over the values. You may, for example, validate the given value in the setter before actually setting
the value.
Getters and setters are fundamental building blocks for encapsulation, which will be covered in the next module.
Constructors
Constructors are special methods invoked when an object is created and are used to initialize them.
A constructor can be used to provide initial values for object attributes.
Using Constructors
The constructor is called when you create an object using the new keyword.
Example:public class MyClass {
public static void main(String[ ] args) {
Vehicle v = new Vehicle("Blue");
}
}
This will call the constructor, which will set the color attribute to "Blue".
Constructors
A single class can have multiple constructors with different numbers of parameters.
The setter methods inside the constructors can be used to set the attribute values.
Example:public class Vehicle {
private String color;
Vehicle() {
this.setColor("Red");
}
Vehicle(String c) {
this.setColor(c);
}
// Setter
public void setColor(String c) {
this.color = c;
}
}
The class above has two constructors, one without any parameters setting the color attribute to a default value of "Red", and
another constructor that accepts a parameter and assigns it to the attribute.
Java automatically provides a default constructor, so all classes have a constructor, whether one is specifically defined or not.
Value Types
Value types are the basic types, and include byte, short, int, long, float, double, boolean, and char.
These data types store the values assigned to them in the corresponding memory locations.
So, when you pass them to a method, you basically operate on the variable's value, rather than on the variable itself.
Example:
The method from the example above takes the value of its parameter, which is why the original variable is not affected and 5 remains as its
value.
Reference Types
A reference type stores a reference (or address) to the memory location where the corresponding data is stored.
When you create an object using the constructor, you create a reference variable.
For example, consider having a Person class defined:
The method celebrateBirthday takes a Person object as its parameter, and increments its attribute.
Because j is a reference type, the method affects the object itself, and is able to change the actual value of its attribute.
Arrays and Strings are also reference data types.
The JDK defines a number of useful classes, one of them being the Math class, which provides predefined methods for mathematical operations.
You do not need to create an object of the Math class to use it. To access it, just type in Math.and the corresponding method.
int a = Math.abs(10); // 10
int b = Math.abs(-20); // 20Try It Yourself
Math.ceil() rounds a floating point value up to the nearest integer value. The rounded value is returned as a double.
Similarly, Math.floor() rounds a floating point value down to the nearest integer value.
Math.pow() takes two parameters and returns the first parameter raised to the power of the second parameter.
There are a number of other methods available in the Math class, including:
sqrt() for square root, sin() for sine, cos() for cosine, and others.
Static
When you declare a variable or a method as static, it belongs to the class, rather than to a specific instance. This means that only one instance of
a static member exists, even if you create multiple objects of the class, or if you don't create any. It will be shared by all objects.
Example:public class Counter {
public static int COUNT=0;
Counter() {
COUNT++;
}
}
The COUNT variable will be shared by all objects of that class.
Now, we can create objects of our Counter class in main, and access the static variable.
Static
Another example of static methods are those of the Math class, which is why you can call them without creating a Math object.
Also, the main method must always be static.
final
Use the final keyword to mark a variable constant, so that it can be assigned only once.
Example:
class MyClass {
public static final double PI = 3.14;
public static void main(String[ ] args) {
System.out.println(PI);
}
}Try It Yourself
Packages
Packages are used to avoid name conflicts and to control access to classes.
A package can be defined as a group made up of similar types of classes, along with sub-packages.
Creating a package in Java is quite easy. Simply right click on your src directory and click New->Package. Give your package a name and
click Finish.
You will notice that the new package appears in the project directory. Now you can move and create classes inside that package. We have
moved our Vehicle, Counter and Animal classes to the package samples.
When you move/create a class in your package, the following code will appear at the top of the list of files.package samples;
This indicates the package to which the class belongs.
Now, we need to import the classes that are inside a package in our main to be able to use them.
The following example shows how to use the Vehicle class of the samples package.import samples.Vehicle;
class MyClass {
public static void main(String[ ] args) {
Vehicle v1 = new Vehicle();
v1.horn();
}
}
Two major results occur when a class is placed in a package. First, the name of the packagebecomes a part of the name of the class. Second, the
name of the package must match the directory structure where the corresponding class file resides.
Use a wildcard to import all classes in a package.
For example, import samples.* will import all classes in the samples package.
Encapsulation
There are 4 core concepts in OOP: encapsulation, inheritance, polymorphism, and abstraction.
The idea behind encapsulation is to ensure that implementation details are not visible to users. The variables of one class will be hidden from
the other classes, accessible only through the methods of the current class. This is called data hiding.
To achieve encapsulation in Java, declare the class' variables as private and provide public setterand getter methods to modify and view the
variables' values.
Inheritance
Inheritance is the process that enables one class to acquire the properties (methods and variables) of another. With inheritance, the information
is placed in a more manageable, hierarchical order.
The class inheriting the properties of another is the subclass (also called derived class, or child class); the class whose properties are inherited is
the superclass (base class, or parent class).
Inheritance
When one class is inherited from another class, it inherits all of the superclass' non-privatevariables and methods.
Example:class Animal {
protected int legs;
public void eat() {
System.out.println("Animal eats");
}
}
class MyClass {
public static void main(String[ ] args) {
Dog d = new Dog();
d.eat();
}
}Try It Yourself
Recall the protected access modifier, which makes the members visible only to the subclasses.
Inheritance
Constructors are not member methods, and so are not inherited by subclasses.
However, the constructor of the superclass is called when the subclass is instantiated.
Example:
class A {
public A() {
System.out.println("New A");
}
}
class B extends A {
public B() {
System.out.println("New B");
}
}
class Program {
public static void main(String[ ] args) {
B obj = new B();
}
}
/*Outputs
"New A"
"New B"
*/Try It Yourself
You can access the superclass from the subclass using the super keyword.
For example, super.var accesses the var member of the superclass.
Polymorphism
Polymorphism, which refers to the idea of "having many forms", occurs when there is a hierarchy of classes related to each other
through inheritance.
A call to a member method will cause a different implementation to be executed, depending on the type of the object invoking the method.
Here is an example: Dog and Cat are classes that inherit from the Animal class. Each class has its own implementation of
the makeSound() method.class Animal {
public void makeSound() {
System.out.println("Grr...");
}
}
class Cat extends Animal {
public void makeSound() {
System.out.println("Meow");
}
}
class Dog extends Animal {
public void makeSound() {
System.out.println("Woof");
}
}
As all Cat and Dog objects are Animal objects, we can do the following in main:public static void main(String[ ] args) {
Animal a = new Dog();
Animal b = new Cat();
}
We've created two reference variables of type Animal, and pointed them to the Cat and Dog objects.
Now, we can call the makeSound() methods.
a.makeSound();
//Outputs "Woof"
b.makeSound();
//Outputs "Meow"Try It Yourself
As the reference variable a contains a Dog object, the makeSound() method of the Dog class will be called.
The same applies to the b variable.
This demonstrates that you can use the Animal variable without actually knowing that it contains an object of the subclass.
This is very useful when you have multiple subclasses of the superclass.
Method Overriding
As we saw in the previous lesson, a subclass can define a behavior that's specific to the subclass type, meaning that a subclass can implement a
parent class method based on its requirement.
This feature is known as method overriding.
Example:
class Animal {
public void makeSound() {
System.out.println("Grr...");
}
}
class Cat extends Animal {
public void makeSound() {
System.out.println("Meow");
}
}Try It Yourself
In the code above, the Cat class overrides the makeSound() method of its superclass Animal.
Method Overloading
When methods have the same name, but different parameters, it is known as method overloading.
This can be very useful when you need the same method functionality for different types of parameters.
The following example illustrates a method that returns the maximum of its two parameters.int max(int a, int b) {
if(a > b) {
return a;
}
else {
return b;
}
}
The method shown above will only work for parameters of type integer.
However, we might want to use it for doubles, as well. For that, you need to overload the max method:
Data abstraction provides the outside world with only essential information, in a process of representing essential features without including
implementation details.
A good real-world example is a book. When you hear the term book, you don't know the exact specifics, such as the page count, the color, or the
size, but you understand the idea, or abstraction, of a book.
The concept of abstraction is that we focus on essential qualities, rather than the specific characteristics of one particular example.
Abstract Class
For example, we can define our Animal class as abstract:abstract class Animal {
int legs = 0;
abstract void makeSound();
}
The makeSound method is also abstract, as it has no implementation in the superclass.
We can inherit from the Animal class and define the makeSound() method for the subclass:
Every Animal makes a sound, but each has a different way to do it. That's why we define an abstract class Animal, and leave the implementation
of how they make sounds to the subclasses.
This is used when there is no meaningful definition for the method in the superclass.
Interfaces
Interfaces
interface Animal {
public void eat();
public void makeSound();
}
class Cat implements Animal {
public void makeSound() {
System.out.println("Meow");
}
public void eat() {
System.out.println("omnomnom");
}
}Try It Yourself
When you implement an interface, you need to override all of its methods.
Type Casting
Assigning a value of one type to a variable of another type is known as Type Casting.
To cast a value to a specific type, place the type in parentheses and position it in front of the value.
Example:
The code above is casting the value 3.14 to an integer, with 3 as the resulting value.
Another example:
double a = 42.571;
int b = (int) a;
System.out.println(b);
//Outputs 42
Java supports automatic type casting of integers to floating points, since there is no loss of precision.
On the other hand, type casting is mandatory when assigning floating point values to integer variables.
Type Casting
Upcasting
Downcasting
Anonymous Classes
Anonymous classes are a way to extend the existing classes on the fly.
For example, consider having a class Machine:class Machine {
public void start() {
System.out.println("Starting...");
}
}
When creating the Machine object, we can change the start method on the fly.
After the constructor call, we have opened the curly braces and have overridden the start method's implementation on the fly.
The @Override annotation is used to make your code easier to understand, because it makes it more obvious when methods are overridden.
Anonymous Classes
The modification is applicable only to the current object, and not the class itself. So if we create another object of that class, the start method's
implementation will be the one defined in the class.
class Machine {
public void start() {
System.out.println("Starting...");
}
}
public static void main(String[ ] args) {
Machine m1 = new Machine() {
@Override public void start() {
System.out.println("Wooooo");
}
};
Machine m2 = new Machine();
m2.start();
}
//Outputs "Starting..."
Inner Classes
class Robot {
int id;
Robot(int i) {
id = i;
Brain b = new Brain();
b.think();
}
}Try It Yourself
The class Robot has an inner class Brain. The inner class can access all of the member variables and methods of its outer class, but it cannot be
accessed from any outside class.
Comparing Objects
Remember that when you create objects, the variables store references to the objects.
So, when you compare objects using the equality testing operator (==), it actually compares the references and not the object values.
Example:
class Animal {
String name;
Animal(String n) {
name = n;
}
}
class MyClass {
public static void main(String[ ] args) {
Animal a1 = new Animal("Robby");
Animal a2 = new Animal("Robby");
System.out.println(a1 == a2);
}
}
//Outputs falseTry It Yourself
Despite having two objects with the same name, the equality testing returns false, because we have two different objects (two different
references or memory locations).
equals()
Each object has a predefined equals() method that is used for semantical equality testing.
But, to make it work for our classes, we need to override it and check the conditions we need.
There is a simple and fast way of generating the equals() method, other than writing it manually.
Just right click in your class, go to Source->Generate hashCode() and equals()...
This will automatically create the necessary methods.class Animal {
String name;
Animal(String n) {
name = n;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Animal other = (Animal) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
The automatically generated hashCode() method is used to determine where to store the object internally. Whenever you implement equals,
you MUST also implement hashCode.
We can run the test again, using the equals method:
You can use the same menu to generate other useful methods, such as getters and setters for your class attributes.
Enums
Enums
After declaring an Enum, we can check for the corresponding values with, for example, a switch statement.
Rank a = Rank.SOLDIER;
switch(a) {
case SOLDIER:
System.out.println("Soldier says hi!");
break;
case SERGEANT:
System.out.println("Sergeant says Hello!");
break;
case CAPTAIN:
System.out.println("Captain says Welcome!");
break;
}
//Outputs "Soldier says hi!"
Enums
You should always use Enums when a variable (especially a method parameter) can only take one out of a small set of possible values.
If you use Enums instead of integers (or String codes), you increase compile-time checking and avoid errors from passing in invalid constants,
and you document which values are legal to use.
Some sample Enum uses include month names, days of the week, deck of cards, etc.
Java API
The Java API is a collection of classes and interfaces that have been written for you to use.
The Java API Documentation with all of the available APIs can be located on the Oracle website at
http://docs.oracle.com/javase/7/docs/api/
Once you locate the package you want to use, you need to import it into your code.
The package can be imported using the import keyword.
For example:import java.awt.*;
The awt package contains all of the classes for creating user interfaces and for painting graphics and images.
The wildcard character (*) is used to import all of the classes in the package.