Classes and Objects
Chapter: 26
Object-oriented Programming
Object-Orientation
Java uses Object-Oriented Programming (OOP), a programming style that is intended to make thinking about programming closer to thinking about the real world.
In OOP, each object is an independent unit with a unique identity, just as objects in the real world are.
An apple is an object; so is a mug. Each has its unique identity. It's possible to have two mugs that look identical, but they are still separate, unique objects.
For example, a car can be red or blue, a mug can be full or empty, and so on. These characteristics are also called attributes. An attribute describes the current state of an object.
In the real world, each object behaves in its own way. The car moves, the phone rings, and so on.
The same applies to objects: behavior is specific to the object's type.
In summary, in object oriented programming, each object has three dimensions: identity, attributes, and behavior.
Attributes describe the object's current state, and what the object is capable of doing is demonstrated through the object's behavior.
Attributes describe the object's current state, and what the object is capable of doing is demonstrated through the object's behavior.
Classes
A class describes what the object will be, but is separate from the object itself.
In other words, classes can be described as blueprints, descriptions, or definitions for an object. You can use the same class as a blueprint for creating multiple objects. The first step is to define the class, which then becomes a blueprint for object creation.
Each class has a name, and each is used to define attributes and behavior.
Some examples of attributes and behavior:
In other words, an object is an instance of a class.
Chapter: 27
Methods
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 {
static void sayHello() {
System.out.println("Hello World!");
}
public static void main(String[ ] args) {
sayHello();
}
}
static void sayHello() {
System.out.println("Hello World!");
}
public static void main(String[ ] args) {
sayHello();
}
}
JAVA
To call a method, type its name and then follow the name with a set of parentheses.
Methods
Fill in the blanks to call the method "hello" from main:
Calling Methods
You can call a method as many times as necessary.
When a method runs, the code jumps down to where the method is defined, executes the code inside of it, then goes back and proceeds to the next line.
Example:
class MyClass {
static void sayHello() {
System.out.println("Hello World!");
}
public static void main(String[ ] args) {
sayHello();
sayHello();
sayHello();
}
}
static void sayHello() {
System.out.println("Hello World!");
}
public static void main(String[ ] args) {
sayHello();
sayHello();
sayHello();
}
}
JAVA
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).
Calling Methods
How many times can you call a method?
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 {
static void sayHello(String name) {
System.out.println("Hello " + name);
}
public static void main(String[ ] args) {
sayHello("David");
sayHello("Amy");
}
}
static void sayHello(String name) {
System.out.println("Hello " + name);
}
public static void main(String[ ] args) {
sayHello("David");
sayHello("Amy");
}
}
JAVA
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.
- 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.
Method Parameters
What output results from this code? public static void main(String[ ] args) { doSomething(4); } static void doSomething(int x) { System.out.println(x*x); }
Chapter: 28
Method Return Types
The Return Type
The return keyword can be used in methods to return a value.
For example, we could define a method named sum that returns the sum of its two parameters.
static int sum(int val1, int val2) {
return val1 + val2;
}
return val1 + val2;
}
JAVA
The static keyword will be discussed in a future lesson.
class MyClass {
static int sum(int val1, int val2) {
return val1 + val2;
}
public static void main(String[ ] args) {
int x = sum(2, 5);
System.out.println(x);
}
}
static int sum(int val1, int val2) {
return val1 + val2;
}
public static void main(String[ ] args) {
int x = sum(2, 5);
System.out.println(x);
}
}
JAVA
When you do not need to return any value from your method, use the keyword void.
Notice the void keyword in the definition of the main method - this means that main does not return anything.
Notice the void keyword in the definition of the main method - this means that main does not return anything.
The Return Type
If you do not want your method to return anything, you should use the keyword:
The Return Type
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);
}
// simply prints"Hello World!"
static void sayHello() {
System.out.println("Hello World!");
}
static int returnFive() {
return 5;
}
// has a parameter
static void sayHelloTo(String name) {
System.out.println("Hello " + name);
}
// simply prints"Hello World!"
static void sayHello() {
System.out.println("Hello World!");
}
JAVA
public static void main(String[ ] args)
JAVA
This definition indicates that the main method takes an array of Strings as its parameters, and does not return a value.
The Return Type
Fill in the blanks to declare an integer, and pass it as a parameter to the test() method.
The Return Type
Let's create a method that takes two parameters of type int and returns the greater one, then call it in main:
public static void main(String[ ] args) {
int res = max(7, 42);
System.out.println(res); //42
}
static int max(int a, int b) {
if(a > b) {
return a;
}
else {
return b;
}
}
int res = max(7, 42);
System.out.println(res); //42
}
static int max(int a, int b) {
if(a > b) {
return a;
}
else {
return b;
}
}
JAVA
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.
The Return Type
What output results from this code? public static void main(String[ ] args) { int x = 10; int y = myFunc(x); System.out.println(y); } public static int myFunc(int x) { return x*3; }
Chapter: 29
Creating Classes and Objects
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. Give your class a name and click Finish to add the new class to your project:
Now lets create a simple method in our new class.
Animal.java
public class Animal {
void bark() {
System.out.println("Woof-Woof");
}
}
void bark() {
System.out.println("Woof-Woof");
}
}
JAVA
Now, in order to use the class and it's methods, we need to declare an object of that class.
Creating Classes
Fill in the blanks to create a class with a single method called "test".
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();
}
}
public static void main(String[ ] args) {
Animal dog = new Animal();
dog.bark();
}
}
JAVA
The dot notation is used to access the object's attributes and methods.
You have just created your first object!
Creating Objects
Drag and drop from the options below to create an object of the A class in the B class and call its "test" method.
Chapter: 30
Class Attributes
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!");
}
}
int maxSpeed;
int wheels;
String color;
double fuelCapacity;
void horn() {
System.out.println("Beep!");
}
}
JAVA
You can define as many attributes and methods as necessary.
Drag and drop from the options below to define a class with these attributes: age of type integer, height as a double, and name as a string.
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();
}
}
public static void main(String[ ] args) {
Vehicle v1 = new Vehicle();
Vehicle v2 = new Vehicle();
v1.color = "red";
v2.horn();
}
}
JAVA
Run the code and see how it works!
Creating Objects
Fill in the blanks to create two objects from the class "People".
Chapter: 31
Access Modifires
Access Modifiers
Now let's discuss the public keyword in front of the main method.
public static void main(String[ ] args)
JAVA
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.
The following choices are available for attributes and methods:
default: A variable or method declared with no access control modifier is available to any other class in the same package.
public: Accessible from any other class.
protected: Provides the same access as the default access modifier, with the addition that subclasses can access protected methods and variables of the superclass (Subclasses and superclasses are covered in upcoming lessons).
private: Accessible only within the declared class itself.
Example:
public class Vehicle {
private int maxSpeed;
private int wheels;
private String color;
private double fuelCapacity;
public void horn() {
System.out.println("Beep!");
}
}
private int maxSpeed;
private int wheels;
private String color;
private double fuelCapacity;
public void horn() {
System.out.println("Beep!");
}
}
JAVA
It's a best practice to keep the variables within a class private. The variables are accessible and modified using Getters and Setters.
Tap Continue to learn about Getters and Setters.
Tap Continue to learn about Getters and Setters.
Chapter: 32
Getters and Setters
Getters & Setters
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.
Example:
public class Vehicle {
private String color;
// Getter
public String getColor() {
return color;
}
// Setter
public void setColor(String c) {
this.color = c;
}
}
private String color;
// Getter
public String getColor() {
return color;
}
// Setter
public void setColor(String c) {
this.color = c;
}
}
JAVA
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.
Getters & Setters
Drag and drop from the options below to define the set and get methods.
Getters & Setters
Once our getter and setter have been defined, we can use it in our main
public static void main(String[ ] args) {
Vehicle v1 = new Vehicle();
v1.setColor("Red");
System.out.println(v1.getColor());
}
Vehicle v1 = new Vehicle();
v1.setColor("Red");
System.out.println(v1.getColor());
}
JAVA
Getters and setters are fundamental building blocks for encapsulation, which will be covered in the next module.
Getters & Setters
What would the name of the setter method for the class variable named "age" be?
Chapter: 33
Constructor
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.
- A constructor name must be same as its class name.
- A constructor must have no explicit return type.
Example of a constructor:
public class Vehicle {
private String color;
Vehicle() {
color = "Red";
}
}
private String color;
Vehicle() {
color = "Red";
}
}
JAVA
A constructor can also take parameters to initialize attributes.
public class Vehicle {
private String color;
Vehicle(String c) {
color = c;
}
}
private String color;
Vehicle(String c) {
color = c;
}
}
JAVA
You can think of constructors as methods that will set up your class by default, so you don’t need to repeat the same code every time.
Constructors
Drag and drop from the options below to create a valid constructor.
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");
}
}
public static void main(String[ ] args) {
Vehicle v = new Vehicle("Blue");
}
}
JAVA
This will call the constructor, which will set the color attribute to "Blue".
Using Constructors
True or false: The constructor must have the same name as the class.
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;
}
}
private String color;
Vehicle() {
this.setColor("Red");
}
Vehicle(String c) {
this.setColor(c);
}
// Setter
public void setColor(String c) {
this.color = c;
}
}
JAVA
Now, we can use the constructors to create objects of our class.
//color will be "Red"
Vehicle v1 = new Vehicle();
//color will be "Green"
Vehicle v2 = new Vehicle("Green");
Vehicle v1 = new Vehicle();
//color will be "Green"
Vehicle v2 = new Vehicle("Green");
JAVA
Java automatically provides a default constructor, so all classes have a constructor, whether one is specifically defined or not.
Constructors
Fill in the blanks.
Practice:
Constructors
Your friend is a cashier at a movie theater. He. knows that you are an awesome java developer so he asked you to help him out and create a program that gets movie title, row, and seat information and prints out a new ticket.
Complete the existing code by adding a constructor to Ticket class so that it can be correctly initialized.
Sample Input
Jaws
5
1
Sample Output
Movie: Jaws
Row: 5
Seat: 1
Note: Comment down your answer.
You can figure out the constructor parameters by looking at the types of data that is being inputted.
Chapter: 34
Value and Refrence Types
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:
public class MyClass {
public static void main(String[ ] args) {
int x = 5;
addOneTo(x);
System.out.println(x);
}
static void addOneTo(int num) {
num = num + 1;
}
}
public static void main(String[ ] args) {
int x = 5;
addOneTo(x);
System.out.println(x);
}
static void addOneTo(int num) {
num = num + 1;
}
}
JAVA
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.
Value Types
What is the output of this code? public static void main(String[ ] args) { int x = 4; square(x); System.out.println(x); } static void square(int x) { x = x*x; }
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:
public class MyClass {
public static void main(String[ ] args) {
Person j;
j = new Person("John");
j.setAge(20);
celebrateBirthday(j);
System.out.println(j.getAge());
}
static void celebrateBirthday(Person p) {
p.setAge(p.getAge() + 1);
}
}
public static void main(String[ ] args) {
Person j;
j = new Person("John");
j.setAge(20);
celebrateBirthday(j);
System.out.println(j.getAge());
}
static void celebrateBirthday(Person p) {
p.setAge(p.getAge() + 1);
}
}
JAVA
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.
Reference Types
What is the output of this code? public static void main(String[ ] args) { Person p = new Person(); p.setAge(25); change(p); System.out.println(p.getAge()); } static void change(Person p) { p.setAge(10); }
Chapter: 35
The Math Class
The Math Class
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.
Math.abs() returns the absolute value of its parameter.
int a = Math.abs(10); // 10
int b = Math.abs(-20); // 20
int b = Math.abs(-20); // 20
JAVA
double c = Math.ceil(7.342); // 8.0
JAVA
double f = Math.floor(7.343); // 7.0
JAVA
int m = Math.max(10, 20); // 20
JAVA
int m = Math.min(10, 20); // 10
JAVA
double p = Math.pow(2, 3); // 8.0
JAVA
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.
sqrt() for square root, sin() for sine, cos() for cosine, and others.
The Math Class
What is the value of the following expression? Math.abs(Math.min(-6, 3));
Chapter: 36
Static
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++;
}
}
public static int COUNT=0;
Counter() {
COUNT++;
}
}
JAVA
Now, we can create objects of our Counter class in main, and access the static variable.
public class MyClass {
public static void main(String[ ] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
System.out.println(Counter.COUNT);
}
}
public static void main(String[ ] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
System.out.println(Counter.COUNT);
}
}
JAVA
You can also access the static variable using any object of that class, such as c1.COUNT.
It’s a common practice to use upper case when naming a static variable, although not mandatory.
Static
Fill in the blank to declare a static variable.
Static
The same concept applies to static methods.
public class Vehicle {
public static void horn() {
System.out.println("Beep");
}
}
public static void horn() {
System.out.println("Beep");
}
}
JAVA
public class MyClass {
public static void main(String[ ] args) {
Vehicle.horn();
}
}
public static void main(String[ ] args) {
Vehicle.horn();
}
}
JAVA
Also, the main method must always be static.
Static
What output results from this code? class Person { public static int pCount; public static void main(String[ ] args) { Person.pCount = 1; Person.pCount++; System.out.println(Person.pCount); } }
Chapter: 37
Final
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);
}
}
public static final double PI = 3.14;
public static void main(String[ ] args) {
System.out.println(PI);
}
}
JAVA
Methods and classes can also be marked final. This serves to restrict methods so that they can't be overridden and classes so that they can't be subclassed.
These concepts will be covered in the next module.
These concepts will be covered in the next module.
Chapter: 38
Packages
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.
package samples;
JAVA
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();
}
}
class MyClass {
public static void main(String[ ] args) {
Vehicle v1 = new Vehicle();
v1.horn();
}
}
JAVA
Use a wildcard to import all classes in a package.
For example, import samples.* will import all classes in the samples package.
For example, import samples.* will import all classes in the samples package.
Packages
How many packages can be contained in a Java program?
Chapter: 39
Module 4 Quiz
Fill in the blank to define a method that does not return a value.
Which access modifier explicitly says that a method or variable of an object can be accessed by code from outside of the class of that object?
Rearrange the code to declare a method returning the greater of the two arguments.
Fill in the blanks to declare a method that takes one argument of type int.
Code Project
Binary Converter
Binary Converter
The binary numeric system uses only two digits: 0 and 1. Computers operate in binary, meaning they store data and perform calculations using only zeros and ones.
You need to make a program to convert integer numbers to their binary representation.
Create a Converter class with a static toBinary() method, which returns the binary version of its argument.
The code in main takes a number as input and calls the corresponding static method. Make sure the code works as expected.
Sample Input:
42
Sample Output:
101010
Note: Comment down your answer.
You can use the following code to convert a number to binary:
You can use the following code to convert a number to binary:
String binary="";
while(num > 0) {
binary = (num%2)+binary;
num /= 2;
}
while(num > 0) {
binary = (num%2)+binary;
num /= 2;
}
JAVA
The code above uses a loop to convert num to binary and stores the result in the binary String.
Comments
Post a Comment