You are on page 1of 52

1

MS1104 – ADVANCED JAVA PROGRAMMING -


THEORY AND PRACTICAL

CHAPTER 2
OBJECT-ORIENTED PROGRAMMING WITH
JAVA

MASTER OF SCIENCE IN INFORMATION TECHNOLOGY


Java Methods

 A method is a block of code which only runs when it is called.


 You can pass data, known as parameters, into a method.

 Methods are used to perform certain actions, and they are also known as functions.

public class MyClass {


static void myMethod() {
// code to be executed
}
}
Example Explained
myMethod() is the name of the method
static means that the method belongs to the MyClass class and not an object of the
MyClass class. You will learn more about objects and how to access methods through
objects later in this tutorial.
void means that this method does not have a return value.
© ISBAT UNIVERSITY – 2019. 11/20/2021
Call a Method
To call a method in Java, write the method's name followed by two parentheses () and
a semicolon;
In the following example, myMethod() is used to print a text (the action), when it is
called:

public class MyClass {


static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
myMethod();
}
}
// Outputs "I just got executed!"
© ISBAT UNIVERSITY – 2019. 11/20/2021
public class MyClass {
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
© ISBAT UNIVERSITY – 2019. 11/20/2021
Java Classes and Objects
 Java is an object-oriented programming language.

 Everything in Java is associated with classes and objects, along with its
attributes and methods. For example: in real life, a car is an object. The
car has attributes, such as weight and color, and methods, such as drive
and brake.
 A Class is like an object constructor, or a "blueprint" for creating
objects.

© ISBAT UNIVERSITY – 2019. 11/20/2021


Create a Class
To create a class, use the keyword class:
MyClass.java
Create a class called "MyClass" with a variable x:

public class MyClass {


int x = 5;
}

© ISBAT UNIVERSITY – 2019. 11/20/2021


Create an Object
In Java, an object is created from a class. We have already created the
class named MyClass, so now we can use this to create objects.

To create an object of MyClass, specify the class name, followed by the


object name, and use the keyword new:
Example
Create an object called "myObj" and print the value of x:

© ISBAT UNIVERSITY – 2019. 11/20/2021


public class MyClass {
int x = 5;

public static void main(String[] args) {


MyClass myObj = new MyClass();
System.out.println(myObj.x);
}
}

© ISBAT UNIVERSITY – 2019. 11/20/2021


Multiple Objects
You can create multiple objects of one class:
public class MyClass {
int x = 5;

public static void main(String[] args) {


MyClass myObj1 = new MyClass(); // Object 1
MyClass myObj2 = new MyClass(); // Object 2
System.out.println(myObj1.x);
System.out.println(myObj2.x);
}
}

© ISBAT UNIVERSITY – 2019. 11/20/2021


Create an object called "myObj" and print the value of x:
public class MyClass {
int x = 5;

public static void main(String[] args) {


MyClass myObj = new MyClass();
System.out.println(myObj.x);
}
}

© ISBAT UNIVERSITY – 2019. 11/20/2021


Java Class Methods
public class MyClass {
static void myMethod() {
System.out.println("Hello World!");
}

public static void main(String[] args) {


myMethod();
}
}

© ISBAT UNIVERSITY – 2019. 11/20/2021


Java Constructors
Constructor in Java is a special method that is used to initialize objects. The constructor is called
when an object of a class is created. It can be used to set initial values for object attributes:
/ Create a MyClass class
public class MyClass {
int x; // Create a class attribute
// Create a class constructor for the MyClass class
public MyClass() {
x = 5; // Set the initial value for the class attribute x
}
public static void main(String[] args) {
MyClass myObj = new MyClass(); // Create an object of class MyClass (This will call the
constructor)
System.out.println(myObj.x); // Print the value of x
}
}
// Outputs 5
© ISBAT UNIVERSITY – 2019. 11/20/2021
➢ The purpose of constructor is to initialize the object of a class while the purpose of a method is
to perform a task by executing java code.
➢ Constructors cannot be abstract, final, static and synchronized while methods can be.
➢ Constructors do not have return types while methods do.
➢ In Java, a constructor is a block of codes similar to the method. It is called when an instance of
the class is created.
➢ At the time of calling constructor, memory for the object is allocated in the memory.
➢ It is a special type of method which is used to initialize the object.
➢ Every time an object is created using the new() keyword, at least one constructor is called.

© ISBAT UNIVERSITY – 2019. 11/20/2021


Rules for creating Java constructor
➢ There are two rules defined for the constructor.

➢ Constructor name must be the same as its class name

➢ A Constructor must have no explicit return type

➢ A Java constructor cannot be abstract, static, final, and synchronized

© ISBAT UNIVERSITY – 2019. 11/20/2021


Types of Java constructors
 There are two types of constructors in Java:

 Default constructor (no-arg constructor)

 Parameterized constructor

Rule: If there is no constructor in a class, compiler automatically creates a


default constructor.

© ISBAT UNIVERSITY – 2019. 11/20/2021


Java Methods
A Java method is a collection of statements that are grouped together to
perform an operation.
 A method is a block of code which only runs when it is called.

 You can pass data, known as parameters, into a method.

 Methods are used to perform certain actions, and they are also known

as functions.
 Why use methods? To reuse code: define the code once, and use it many

times.

© ISBAT UNIVERSITY – 2019. 11/20/2021


Method Overloading in Java
 If a class has multiple methods having same name but different in

parameters, it is known as Method Overloading.


 If we have to perform only one operation, having same name of the

methods increases the readability of the program.


Method Overloading is a feature that allows a class to have more than one
method having the same name, if their argument lists are different.

© ISBAT UNIVERSITY – 2019. 11/20/2021


Three ways to overload a method
1. Number of parameters.
add(int, int)
add(int, int, int)
2. Data type of parameters.
add(int, int)
add(int, float)
3. Sequence/Order of Data type of parameters.
add(int, float)
add(float, int)
© ISBAT UNIVERSITY – 2019. 11/20/2021
Java Modifiers
By now, you are quite familiar with the public keyword that appears in
almost all of our examples:
public class MyClass
The public keyword is an access modifier, meaning that it is used to set the
access level for classes, attributes, methods and constructors.
We divide modifiers into two groups:
Access Modifiers - controls the access level
Non-Access Modifiers - do not control access level, but provides other
functionality.
© ISBAT UNIVERSITY – 2019. 11/20/2021
First Java Program
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
Output:
Hello Java

© ISBAT UNIVERSITY – 2019. 11/20/2021


 Parameters used in First Java Program
 Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
 class keyword is used to declare a class in java.
 public keyword is an access modifier which represents visibility. It means it is visible to all.
 static is a keyword. If we declare any method as static, it is known as the static method. The
core advantage of the static method is that there is no need to create an object to invoke the
static method. The main method is executed by the JVM, so it doesn't require to create an
object to invoke the main method. So it saves memory.

© ISBAT UNIVERSITY – 2019. 11/20/2021


 void is the return type of the method. It means it doesn't return any
value.
 main represents the starting point of the program.
 String[] args is used for command line argument. We will learn it later.
 System.out.println() is used to print statement. Here, System is a class,
out is the object of PrintStream class, println() is the method of
PrintStream class. We will learn about the internal working of
System.out.println statement later.

© ISBAT UNIVERSITY – 2019. 11/20/2021


Simple Addition
public class MyClass
{
public static void main(String args[])
{
int x=10;
int y=25;
int z=x+y;
System.out.println("Sum of x+y = " + z);
}

}
© ISBAT UNIVERSITY – 2019. 11/20/2021
Access Modifiers
Modifier Description

public The class is accessible by any other class


default The class is only accessible by classes in the same package. This is used when
you don't specify a modifier.

Modifier Description
public The code is accessible for all classes
private The code is only accessible within the declared class
default The code is only accessible in the same package. This is used when you don't
specify a modifier.
protected The code is accessible in the same package and subclasses.

© ISBAT UNIVERSITY – 2019. 11/20/2021


Non-Access Modifiers
For classes, you can use either final or abstract:

Modifier Description
final The class cannot be inherited by other classes (You will learn more about inheritance in
the Inheritance chapter)
abstract The class cannot be used to create objects (To access an abstract class, it must be inherited
from another class. You will learn more about inheritance in the Inheritance chapter)

© ISBAT UNIVERSITY – 2019. 11/20/2021


For attributes and methods, you can use the one of the following:
Modifier Description
final Attributes and methods cannot be overridden/modified
static Attributes and methods belongs to the class, rather than an object
abstract Can only be used in an abstract class, and can only be used on methods. The method does
not have a body, for example abstract void run();

transient Attributes and methods are skipped when serializing the object containing them

synchronized Methods can only be accessed by one thread at a time


volatile The value of an attribute is not cached thread-locally, and is always read from the "main
memory"

© ISBAT UNIVERSITY – 2019. 11/20/2021


Java 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 (only accessible within the


same class)
provide public setter and getter methods to access and update the value of
a private variable

© ISBAT UNIVERSITY – 2019. 11/20/2021


Java Inheritance
In Java, it is possible to inherit attributes and methods from one class to
another. We group the "inheritance concept" into two categories:

subclass (child) - the class that inherits from another class


superclass (parent) - the class being inherited from
To inherit from a class, use the extends keyword.

In the example below, the Car class (subclass) inherits the attributes and
methods from the Vehicle class (superclass):
© ISBAT UNIVERSITY – 2019. 11/20/2021
class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}
}
class Car extends Vehicle {
private String modelName = "Mustang"; // Car attribute
public static void main(String[] args) {
// Create a myCar object
Car myCar = new Car();
// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();

// Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class
System.out.println(myCar.brand + " " + myCar.modelName);
} © ISBAT UNIVERSITY – 2019. 11/20/2021

}
Java Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes that are related to each other
by inheritance.
Like we specified in the previous chapter; Inheritance lets us inherit attributes and methods from another
class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action
in different ways.

For example, think of a superclass called Animal that has a method called animalSound(). Subclasses of
Animals could be Pigs, Cats, Dogs, Birds - And they also have their own implementation of an animal sound
(the pig oinks, and the cat meows, etc.):

© ISBAT UNIVERSITY – 2019. 11/20/2021


class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
class Pig extends Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
}
}
class Dog extends Animal {
public void animalSound() {
System.out.println("The dog says: bow wow");
}
}
© ISBAT UNIVERSITY – 2019. 11/20/2021
Java User Input
The Scanner class is used to get user input, and it is found in the java.util
package.
To use the Scanner class, create an object of the class and use any of the
available methods found in the Scanner class documentation. In our
example, we will use the nextLine() method, which is used to read Strings:

© ISBAT UNIVERSITY – 2019. 11/20/2021


import java.util.Scanner; // Import the Scanner class
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");

String userName = myObj.nextLine(); // Read user input


System.out.println("Username is: " + userName); // Output user input
}
}
© ISBAT UNIVERSITY – 2019. 11/20/2021
Inheritance
The process by which one class acquires the properties(data members) and
functionalities(methods) of another class is called inheritance. The aim of inheritance
is to provide the reusability of code so that a class has to write only the unique features
and rest of the common properties and functionalities can be extended from the
another class.
Child Class:
The class that extends the features of another class is known as child class, sub class
or derived class.
Parent Class:
The class whose properties and functionalities are used(inherited) by another class is
known as parent class, super class or Base class.

© ISBAT UNIVERSITY – 2019. 11/20/2021


class Teacher {
String designation = "Teacher";
String collegeName = "Beginnersbook";
void does(){
System.out.println("Teaching");
}
}

public class PhysicsTeacher extends Teacher{


String mainSubject = "Physics";
public static void main(String args[]){
PhysicsTeacher obj = new PhysicsTeacher();
System.out.println(obj.collegeName);
System.out.println(obj.designation);
System.out.println(obj.mainSubject);
obj.does();
}
© ISBAT UNIVERSITY – 2019. 11/20/2021
}
An abstract class can have both abstract and regular methods:
abstract class Animal {
public abstract void animalSound();
public void sleep() {
System.out.println("Zzz");
}
}
From the example above, it is not possible to create an object of the
Animal class:
Animal myObj = new Animal(); // will generate an error
© ISBAT UNIVERSITY – 2019. 11/20/2021
To access the abstract class, it must be inherited from another class. Let's
convert the Animal class we used in the Polymorphism

© ISBAT UNIVERSITY – 2019. 11/20/2021


Example
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep() {
System.out.println("Zzz");
}
}

// Subclass (inherit from Animal)


class Pig extends Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
}
© ISBAT UNIVERSITY – 2019. 11/20/2021
Java Interface
Another way to achieve abstraction in Java, is with interfaces.

An interface is a completely "abstract class" that is used to group related


methods w
Example
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}ith empty bodies:
© ISBAT UNIVERSITY – 2019. 11/20/2021
Java Interface
An interface is an abstract "class" that is used to group related methods
with "empty" bodies:
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}

To access the interface methods, the interface must be "implemented"


(kinda like inherited) by another class with the implements keyword
(instead of extends). The body of the interface method is provided by the
"implement" class:
© ISBAT UNIVERSITY – 2019. 11/20/2021
To access the interface methods, the interface must be "implemented"
(kinda like inherited) by another class with the implements keyword
(instead of extends). The body of the interface method is provided by the
"implement" class:

© ISBAT UNIVERSITY – 2019. 11/20/2021


Example
// Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}

// Pig "implements" the Animal interface


class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}

class MyMainClass {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
} © ISBAT UNIVERSITY – 2019. 11/20/2021
}
Notes on Interfaces:
Like abstract classes, interfaces cannot be used to create objects (in the example above, it is not
possible to create an "Animal" object in the MyMainClass)
Interface methods does not have a body - the body is provided by the "implement" class
On implementation of an interface, you must override all of its methods
Interface methods are by default abstract and public
Interface attributes are by default public, static and final
An interface cannot contain a constructor (as it cannot be used to create objects)
Why And When To Use Interfaces?
1) To achieve security - hide certain details and only show the important details of an object
(interface).

2) Java does not support "multiple inheritance" (a class can only inherit from one superclass).
However, it can be achieved with interfaces, because the class can implement multiple interfaces.
Note: To implement multiple interfaces, separate them with a comma (see example below).

© ISBAT UNIVERSITY – 2019. 11/20/2021


Multiple Interfaces
To implement multiple interfaces, separate them with a comma:

© ISBAT UNIVERSITY – 2019. 11/20/2021


Example
interface FirstInterface {
public void myMethod(); // interface method
}

interface SecondInterface {
public void myOtherMethod(); // interface method
}

// DemoClass "implements" FirstInterface and SecondInterface


class DemoClass implements FirstInterface, SecondInterface {
public void myMethod() {
System.out.println("Some text..");
}
public void myOtherMethod() {
System.out.println("Some other text...");
}
}

class MyMainClass {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
© ISBAT
} UNIVERSITY – 2019. 11/20/2021
Final Keyword
The final keyword in java is used to restrict the user. The java final
keyword can be used in many context. Final can be:
 variable

 method

 class

When to use a final variable :


 The only difference between a normal variable and a final variable is
that we can re-assign value to a normal variable but we cannot change
the value of a final variable once assigned. Hence final variables must
be used only for the values that we want to remain constant throughout
the execution of program.
© ISBAT UNIVERSITY – 2019. 11/20/2021
Final variable
 If you make any variable as final, you cannot change the value

of final variable(It will be constant).


Example of final variable
 There is a final variable speedlimit, we are going to change
the value of this variable, but It can't be changed because final
variable once assigned a value can never be changed.

© ISBAT UNIVERSITY – 2019. 11/20/2021


class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}
Compile by: javac Bike9.java
 236.3/Bike9.java:4: error: cannot assign a value to final variable speedlimit
speedlimit=400;
1 error

© ISBAT UNIVERSITY – 2019. 11/20/2021


Java final method
 If you make any method as final, you cannot override it.
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
Compile by: javac Honda.java
honda.run(); 236.3/Honda.java:6: error: run() in Honda cannot override run()
} in Bike
ly with 100kmph");}
}
^
overridden method is final
1 error

© ISBAT UNIVERSITY – 2019. 11/20/2021


Java final class
If you make any class as final, you cannot extend it.
final class Bike{}

class Honda1 extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}
O/P
cannot inherit from final Bike
© ISBAT UNIVERSITY – 2019. 11/20/2021
Is final method inherited?
 Ans) Yes, final method is inherited but you cannot override it.

For Example:
class Bike{
final void run(){System.out.println("running...");}
}
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2().run();
}
}
© ISBAT UNIVERSITY – 2019. 11/20/2021
Thank You

© ISBAT UNIVERSITY – 2019. 11/20/2021

You might also like