0% found this document useful (0 votes)
46 views41 pages

Oop

This document provides an overview of key concepts in object-oriented programming with Java including: what object-oriented programming and Java are; why use Java; Java syntax; methods; classes and objects; constructors; modifiers like access, final, static, and abstract; exception handling; packages; inheritance; polymorphism; and interfaces. It includes examples to illustrate concepts like method overloading, overriding, encapsulation with getters and setters, importing packages and classes, inheritance with subclasses and superclasses, abstract classes and methods, and implementing interfaces.

Uploaded by

Danish Khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views41 pages

Oop

This document provides an overview of key concepts in object-oriented programming with Java including: what object-oriented programming and Java are; why use Java; Java syntax; methods; classes and objects; constructors; modifiers like access, final, static, and abstract; exception handling; packages; inheritance; polymorphism; and interfaces. It includes examples to illustrate concepts like method overloading, overriding, encapsulation with getters and setters, importing packages and classes, inheritance with subclasses and superclasses, abstract classes and methods, and implementing interfaces.

Uploaded by

Danish Khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Table of Contents

What is OOP? ........................................................................................................................................ 3


What is Java? ........................................................................................................................................ 3
Why Use Java? ..................................................................................................................................... 4
Java Syntax ............................................................................................................................................. 4
Example explained........................................................................................................................... 4
The main Method ................................................................................................................................... 5
System.out.println() ................................................................................................................................ 5
Method Overloading .............................................................................................................................. 6
Example............................................................................................................................................... 6
Example............................................................................................................................................... 6
Method Overriding in Java .................................................................................................................... 7
Super Keyword in Java........................................................................................................................... 8
Exception Handling in Java ................................................................................................................... 8
Throw and throws in Java ..................................................................................................................... 9
Java throw Example............................................................................................................................. 10
Java Methods........................................................................................................................................... 11
Create a Method ................................................................................................................................... 11
Example............................................................................................................................................. 12
Java Classes/Objects............................................................................................................................. 12
Create a Class ........................................................................................................................................ 13
MyClass.java..................................................................................................................................... 13
Create an Object ................................................................................................................................... 14
Example............................................................................................................................................. 14
Java Constructors.................................................................................................................................. 14
Example............................................................................................................................................. 14
Constructor Parameters ....................................................................................................................... 15
Example............................................................................................................................................. 16
Example............................................................................................................................................. 16
Modifiers ................................................................................................................................................ 17
Access Modifiers ................................................................................................................................... 17

1
Non-Access Modifiers .......................................................................................................................... 19
Final ........................................................................................................................................................ 20
Example............................................................................................................................................. 20
Static ....................................................................................................................................................... 21
Example............................................................................................................................................. 21
Abstract .................................................................................................................................................. 22
Example............................................................................................................................................. 22
Encapsulation ........................................................................................................................................ 24
Get and Set ............................................................................................................................................ 24
Example............................................................................................................................................. 24
Java Packages & API ............................................................................................................................ 25
Built-in Packages .................................................................................................................................. 25
Syntax ................................................................................................................................................ 26
Import a Class ....................................................................................................................................... 26
Example............................................................................................................................................. 26
Example............................................................................................................................................. 26
Import a Package .................................................................................................................................. 27
Example............................................................................................................................................. 27
User-defined Packages ........................................................................................................................ 27
Example............................................................................................................................................. 27
MyPackageClass.java ..................................................................................................................... 28
Java Inheritance ...................................................................................................................................... 28
Java Inheritance (Subclass and Superclass) ....................................................................................... 28
Example............................................................................................................................................. 28
The final Keyword ................................................................................................................................. 30
Java Polymorphism ............................................................................................................................... 30
Example............................................................................................................................................. 31
Example............................................................................................................................................. 31
Java Abstract Classes and Methods ................................................................................................... 33
Example............................................................................................................................................. 34
Java Interface......................................................................................................................................... 35

2
Example............................................................................................................................................. 35
Example............................................................................................................................................. 36
Multiple Interfaces ................................................................................................................................ 37
Example............................................................................................................................................. 37
Loops ...................................................................................................................................................... 38
Java While Loop .................................................................................................................................... 39
Syntax ................................................................................................................................................ 39
Example............................................................................................................................................. 39
The Do/While Loop .............................................................................................................................. 39
Syntax ................................................................................................................................................ 40
Example............................................................................................................................................. 40
Java For Loop ........................................................................................................................................ 40
Syntax ................................................................................................................................................ 40
Example............................................................................................................................................. 41

What is OOP?

OOP stands for Object-Oriented Programming.

Procedural programming is about writing procedures or methods that perform


operations on the data, while object-oriented programming is about creating objects that
contain both data and methods.

Object-oriented programming has several advantages over procedural programming:

 OOP is faster and easier to execute


 OOP provides a clear structure for the programs
 OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the
code easier to maintain, modify and debug
 OOP makes it possible to create full reusable applications with less code and
shorter development time

What is Java?

Java is a popular programming language, created in 1995.

It is owned by Oracle, and more than 3 billion devices run Java.

3
It is used for:

 Mobile applications (specially Android apps)


 Desktop applications
 Web applications
 Web servers and application servers
 Games
 Database connection
 And much, much more!

Why Use Java?

 Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
 It is one of the most popular programming language in the world
 It has a large demand in the current job market
 It is easy to learn and simple to use
 It is open-source and free
 It is secure, fast and powerful
 It has a huge community support (tens of millions of developers)
 Java is an object oriented language which gives a clear structure to programs
and allows code to be reused, lowering development costs
 As Java is close to C++ and C#, it makes it easy for programmers to switch to
Java or vice versa

Java Syntax

In the previous chapter, we created a Java file called Main.java, and we used the
following code to print "Hello World" to the screen:

Main.java

public class Main {

public static void main(String[] args) {

System.out.println("Hello World");

Example explained

Every line of code that runs in Java must be inside a class. In our example, we named
the class Main. A class should always start with an uppercase first letter.

4
Note: Java is case-sensitive: "MyClass" and "myclass" has different meaning.

The name of the java file must match the class name. When saving the file, save it
using the class name and add ".java" to the end of the filename. To run the example
above on your computer, make sure that Java is properly installed: Go to the Get
Started Chapter for how to install Java. The output should be:

Hello World

The main Method

The main() method is required and you will see it in every Java program:

public static void main(String[] args)

Any code inside the main() method will be executed. Don't worry about the keywords
before and after main. You will get to know them bit by bit while reading this tutorial.

For now, just remember that every Java program has a class name which must match
the filename, and that every program must contain the main() method.

System.out.println()

Inside the main() method, we can use the println() method to print a line of text to the
screen:

public static void main(String[] args) {

System.out.println("Hello World");

Note: The curly braces {} marks the beginning and the end of a block of code.

System is a built-in Java class that contains useful members, such as out, which is short
for "output". The println() method, short for "print line", is used to print a value to the
screen (or a file).

Don't worry too much about System, out and println(). Just know that you need them
together to print stuff to the screen.

You should also note that each code statement must end with a semicolon (;).

5
Method Overloading
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.

Suppose you have to perform addition of the given numbers but there can be any number
of arguments, if you write the method such as a(int,int) for two parameters, and
b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behavior of the method because its name differs.

With method overloading, multiple methods can have the same name with
different parameters:

Example
int myMethod(int x)

float myMethod(float x)

double myMethod(double x, double y)

Consider the following example, which have two methods that add numbers of
different type:

Example
static int plusMethodInt(int x, int y) {

return x + y;

static double plusMethodDouble(double x, double y) {

return x + y;

6
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);

Run example »

Instead of defining two methods that should do the same thing, it is better to
overload one.

In the example below, we overload the plusMethod method to work for


both int and double:

Method Overriding in Java


If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.

In other words, If a subclass provides the specific implementation of the method that has
been declared by one of its parent class, it is known as method overriding.

1. //Java Program to demonstrate why we need method overriding


2. //Here, we are calling the method of parent class with child
3. //class object.
4. //Creating a parent class
5. class Vehicle{
6. void run(){System.out.println("Vehicle is running");}
7. }
8. //Creating a child class
9. class Bike extends Vehicle{
10. public static void main(String args[]){
11. //creating an instance of child class
12. Bike obj = new Bike();
13. //calling the method with child class instance

7
14. obj.run();
15. }
16. }

Super Keyword in Java


The super keyword in Java is a reference variable which is used to refer immediate parent
class object.

Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.

We can use super keyword to access the data member or field of parent class. It is used if
parent class and child class have same fields.

1. class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}

Exception Handling in Java


The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained. Exception Handling
is a mechanism to handle runtime errors such as ClassNotFoundException, IOException,
SQLException, RemoteException, etc.

8
In this tutorial, we will learn about Java exceptions, it's types, and the difference between
checked and unchecked exceptions.

JavaExceptionExample.java

public class JavaExceptionExample{


public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}

Throw and throws in Java


The throw and throws is the concept of exception handling where the throw keyword
throw the exception explicitly from a method or a block of code whereas the throws
keyword is used in signature of the method.

There are many differences between throw and throws keywords. A list of differences
between throw and throws are given below:

Sr. Basis of Differences throw throws


no.

1. Definition Java throw keyword is Java throws keyword is


used throw an used in the method
exception explicitly in signature to declare an
the code, inside the exception which might
function or the block of be thrown by the
code. function while the
execution of the code.

9
2. Type of exception Using Using throws keyword,
throw keyword, we can we can declare both
only propagate unchecked checked and
exception i.e., the checked unchecked exceptions.
exception cannot be However, the throws
propagated using throw keyword can be used to
only. propagate checked
exceptions only.

3. Syntax The throw keyword is The throws keyword is


followed by an instance followed by class names
of Exception to be of Exceptions to be
thrown. thrown.

4. Declaration throw is used within throws is used with the


the method. method signature.

5. Internal implementation We are allowed to We can declare multiple


throw only one exceptions using throws
exception at a time i.e. keyword that can be
we cannot throw thrown by the method.
multiple exceptions. For example, main()
throws IOException,
SQLException.

Java throw Example


TestThrow.java

public class TestThrow {


//defining a method
public static void checkNum(int num) {
if (num < 1) {
throw new ArithmeticException("\nNumber is negative, cannot calculate square");
}
else {
System.out.println("Square of " + num + " is " + (num*num));

10
}
}
//main method
public static void main(String[] args) {
TestThrow obj = new TestThrow();
obj.checkNum(-3);
System.out.println("Rest of the code..");
}
}

Java Methods
❮ PreviousNext ❯

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.

Create a Method
A method must be declared within a class. It is defined with the name of the
method, followed by parentheses (). Java provides some pre-defined methods,
such as System.out.println(), but you can also create your own methods to
perform certain actions:

11
Example
Create a method inside MyClass:

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. You will learn
more about return values later in this chapter

Java Classes/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.

Classes A Class is like an object constructor, or a "blueprint" for creating


objects. An object is an instance of a class. A class is a template or blueprint from which
objects are created. So, an object is the instance(result) of a class.

Object Definitions:

o An object is a real-world entity.


o An object is a runtime entity.

12
o The object is an entity which has state and behavior.
o The object is an instance of a class.

Objects An entity that has state and behavior is known as an object e.g., chair,
bike, marker, pen, table, car, etc. It can be physical or logical (tangible and intangible). The
example of an intangible object is the banking system.

An object has three characteristics:

o State: represents the data (value) of an object.


o Behavior: represents the behavior (functionality) of an object such as deposit,
withdraw, etc.
o Identity: An object identity is typically implemented via a unique ID. The value of
the ID is not visible to the external user. However, it is used internally by the JVM
to identify each object uniquely.

Create a Class
To create a class, use the keyword class:

MyClass.java
Create a class named "MyClass" with a variable x:

public class MyClass {

int x = 5;

Remember from the Java Syntax chapter that a class should always start with
an uppercase first letter, and that the name of the java file should match the
class name.

13
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:

public class MyClass {

int x = 5;

public static void main(String[] args) {

MyClass myObj = new MyClass();

System.out.println(myObj.x);

Java Constructors
A 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:

Example
Create a constructor:

// Create a MyClass class

public class MyClass {

14
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

Run example »

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.

15
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:

Example
public class MyClass {

int x;

public MyClass(int y) {

x = y;

public static void main(String[] args) {

MyClass myObj = new MyClass(5);

System.out.println(myObj.x);

// Outputs 5

Run example »

You can have as many parameters as you want:

Example
public class Car {

int modelYear;

String modelName;

16
public Car(int year, String name) {

modelYear = year;

modelName = name;

public static void main(String[] args) {

Car myCar = new Car(1969, "Mustang");

System.out.println(myCar.modelYear + " " + myCar.modelName);

// Outputs 1969 Mustang

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

Access Modifiers
17
For classes, you can use either public or default:

Modifier Description Try it

public The class is accessible by any other class Try it


»

default The class is only accessible by classes in the same package. This is used Try it
when you don't specify a modifier. You will learn more about packages »
in the Packages chapter

For attributes, methods and constructors, you can use the one of the
following:

Modifier Description Try it

public The code is accessible for all classes Try it


»

private The code is only accessible within the declared class Try it
»

default The code is only accessible in the same package. This is used when Try it
you don't specify a modifier. You will learn more about packages in »
the Packages chapter

18
protected The code is accessible in the same package and subclasses. You will Try it
learn more about subclasses and superclasses in the Inheritance »
chapter

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

Modifier Description Try it

final The class cannot be inherited by other classes (You will learn more Try
about inheritance in the Inheritance chapter) it »

abstract The class cannot be used to create objects (To access an abstract class, Try
it must be inherited from another class. You will learn more about it »
inheritance and abstraction in
the Inheritance and Abstraction chapters)

For attributes and methods, you can use the one of the following:

Modifier Description

final Attributes and methods cannot be overridden/modified

19
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();. The
body is provided by the subclass (inherited from). You will learn more
about inheritance and abstraction in
the Inheritance and Abstraction chapters

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"

Final
If you don't want the ability to override existing attribute values, declare
attributes as final:

Example
public class MyClass {

final int x = 10;

final double PI = 3.14;

20
public static void main(String[] args) {

MyClass myObj = new MyClass();

myObj.x = 50; // will generate an error: cannot assign a value to a


final variable

myObj.PI = 25; // will generate an error: cannot assign a value to a


final variable

System.out.println(myObj.x);

Run example »

Static
A static method means that it can be accessed without creating an object of the
class, unlike public:

Example
An example to demonstrate the differences between static and public methods:

public class MyClass {

// Static method

static void myStaticMethod() {

System.out.println("Static methods can be called without creating


objects");

21
// Public method

public void myPublicMethod() {

System.out.println("Public methods must be called by creating


objects");

// Main method

public static void main(String[ ] args) {

myStaticMethod(); // Call the static method

// myPublicMethod(); This would output an error

MyClass myObj = new MyClass(); // Create an object of MyClass

myObj.myPublicMethod(); // Call the public method

Run example »

Abstract
An abstract method belongs to an abstract class, and it does not have a body.
The body is provided by the subclass:

Example
// Code from filename: Person.java

22
// abstract class
abstract class Person {

public String fname = "John";

public int age = 24;

public abstract void study(); // abstract method

// Subclass (inherit from Person)

class Student extends Person {

public int graduationYear = 2018;

public void study() { // the body of the abstract method is provided


here

System.out.println("Studying all day long");

// End code from filename: Person.java

// Code from filename: MyClass.java

class MyClass {

public static void main(String[] args) {

// create an object of the Student class (which inherits attributes


and methods from Person)

Student myObj = new Student();

System.out.println("Name: " + myObj.fname);

System.out.println("Age: " + myObj.age);

System.out.println("Graduation Year: " + myObj.graduationYear);

23
myObj.study(); // call abstract method
}

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
public class Person {

private String name; // private = restricted access

// Getter

public String getName() {

return name;

24
// Setter

public void setName(String newName) {

this.name = newName;

Example explained

The get method returns the value of the variable name.

The set method takes a parameter (newName) and assigns it to the name variable.
The this keyword is used to refer to the current object.

Java Packages & API


A package in Java is used to group related classes. Think of it as a folder in a
file directory. We use packages to avoid name conflicts, and to write a better
maintainable code. Packages are divided into two categories:

 Built-in Packages (packages from the Java API)


 User-defined Packages (create your own packages)

Built-in Packages
The Java API is a library of prewritten classes, that are free to use, included in
the Java Development Environment.

The library contains components for managing input, database programming,


and much much more. The complete list can be found at Oracles
website: https://docs.oracle.com/javase/8/docs/api/.

The library is divided into packages and classes. Meaning you can either
import a single class (along with its methods and attributes), or a whole
package that contain all the classes that belong to the specified package.
25
To use a class or a package from the library, you need to use
the import keyword:

Syntax
import package.name.Class; // Import a single class

import package.name.*; // Import the whole package

Import a Class
If you find a class you want to use, for example, the Scanner class, which is
used to get user input, write the following code:

Example
import java.util.Scanner;

In the example above, java.util is a package, while Scanner is a class of


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 a complete line:

Example
Using the Scanner class to get user input:

import java.util.Scanner;

class MyClass {

public static void main(String[] args) {

Scanner myObj = new Scanner(System.in);

System.out.println("Enter username");

26
String userName = myObj.nextLine();

System.out.println("Username is: " + userName);

Run example »

Import a Package
There are many packages to choose from. In the previous example, we used
the Scanner class from the java.util package. This package also contains date
and time facilities, random-number generator and other utility classes.

To import a whole package, end the sentence with an asterisk sign (*). The
following example will import ALL the classes in the java.util package:

Example
import java.util.*;

Run example »

User-defined Packages
To create your own package, you need to understand that Java uses a file
system directory to store them. Just like folders on your computer:

Example
└── root
└── mypack
└── MyPackageClass.java

To create a package, use the package keyword:

27
MyPackageClass.java
package mypack;

class MyPackageClass {

public static void main(String[] args) {

System.out.println("This is my package!");

Java Inheritance
❮ PreviousNext ❯

Java Inheritance (Subclass and Superclass)


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):

Example
class Vehicle {

protected String brand = "Ford"; // Vehicle attribute

public void honk() { // Vehicle method

28
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);

Run example »

Did you notice the protected modifier in Vehicle?

We set the brand attribute in Vehicle to a protected access modifier. If it was


set to private, the Car class would not be able to access it.

29
Why And When To Use "Inheritance"?
- It is useful for code reusability: reuse attributes and methods of an existing
class when you create a new class.

Tip: Also take a look at the next chapter, Polymorphism, which uses inherited
methods to perform different tasks.

The final Keyword


If you don't want other classes to inherit from a class, use the final keyword:

If you try to access a final class, Java will generate an error:

final class Vehicle {

...

class Car extends Vehicle {

...

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.):

30
Example
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");

Remember from the Inheritance chapter that we use the extends keyword to
inherit from a class.

Now we can create Pig and Dog objects and call the animalSound() method on both
of them:

Example
class Animal {

public void animalSound() {

31
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");

class MyMainClass {

public static void main(String[] args) {

Animal myAnimal = new Animal(); // Create a Animal object

Animal myPig = new Pig(); // Create a Pig object

Animal myDog = new Dog(); // Create a Dog object

myAnimal.animalSound();

myPig.animalSound();

myDog.animalSound();

32
}

Java Abstract Classes and Methods


Data abstraction is the process of hiding certain details and showing only
essential information to the user.
Abstraction can be achieved with either abstract classes or interfaces (which
you will learn more about in the next chapter).

The abstract keyword is a non-access modifier, used for classes and methods:

 Abstract class: is a restricted class that cannot be used to create objects


(to access it, it must be inherited from another class).

 Abstract method: can only be used in an abstract class, and it does not
have a body. The body is provided by the subclass (inherited from).

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

To access the abstract class, it must be inherited from another class. Let's
convert the Animal class we used in the Polymorphism chapter to an abstract
class:

33
Remember from the Inheritance chapter that we use the extends keyword to
inherit from a class.

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");

class MyMainClass {

public static void main(String[] args) {

Pig myPig = new Pig(); // Create a Pig object

myPig.animalSound();

34
myPig.sleep();

Java Interface
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.

In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.

Java Interface also represents the IS-A relationship.

It cannot be instantiated just like the abstract class.

Since Java 8, we can have default and static methods in an interface.

Since Java 9, we can have private methods in an interface.

Example
// 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:

35
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();

36
}

Run example »

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 do 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).

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

Example
interface FirstInterface {

public void myMethod(); // interface method

37
interface SecondInterface {

public void myOtherMethod(); // interface method

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();

Loops
Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code
more readable.

38
Java While Loop
The while loop loops through a block of code as long as a specified condition
is true:

Syntax
while (condition) {

// code block to be executed

In the example below, the code in the loop will run, over and over again, as
long as a variable (i) is less than 5:

Example
int i = 0;

while (i < 5) {

System.out.println(i);

i++;

Run example »

Note: Do not forget to increase the variable used in the condition, otherwise
the loop will never end!

The Do/While Loop


The do/while loop is a variant of the while loop. This loop will execute the code
block once, before checking if the condition is true, then it will repeat the loop
as long as the condition is true.

39
Syntax
do {

// code block to be executed

while (condition);

The example below uses a do/while loop. The loop will always be executed at
least once, even if the condition is false, because the code block is executed
before the condition is tested:

Example
int i = 0;
do {

System.out.println(i);

i++;

while (i < 5);

Run example »

Do not forget to increase the variable used in the condition, otherwise the loop
will never end!

Java For Loop


When you know exactly how many times you want to loop through a block of
code, use the for loop instead of a while loop:

Syntax
for (statement 1; statement 2; statement 3) {

// code block to be executed

40
Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

Example
for (int i = 0; i < 5; i++) {

System.out.println(i);

Run example »

Example explained

Statement 1 sets a variable before the loop starts (int i = 0).

Statement 2 defines the condition for the loop to run (i must be less than 5). If
the condition is true, the loop will start over again, if it is false, the loop will
end.

Statement 3 increases a value (i++) each time the code block in the loop has
been executed.

41

You might also like