0% found this document useful (0 votes)
8 views62 pages

Java OOP: Classes, Objects, and Methods

Uploaded by

alirbashir174
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)
8 views62 pages

Java OOP: Classes, Objects, and Methods

Uploaded by

alirbashir174
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

OOP WITH JAVA

Java OOP

Java - 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

Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of
code. You should extract out the codes that are common for the application, and place
them at a single place and reuse them instead of repeating it.

Java - What are Classes and Objects?


Classes and objects are the two main aspects of object-oriented programming.

Look at the following illustration to see the difference between class and objects:
OOP WITH JAVA

class
Fruit

objects
Apple

Banana

Mango

Another example:

class
Car

objects
Volvo

Audi

Toyota

So, a class is a template for objects, and an object is an instance of a class.

When the individual objects are created, they inherit all the variables and methods from
the class.
OOP WITH JAVA

Java Classes and Objects

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.

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

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

[Link] your own Java Server


Create a class named "Main" with a variable x:

public class Main {

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.

Create an Object
OOP WITH JAVA

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

To create an object of Main, 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 Main {

int x = 5;

public static void main(String[] args) {

Main myObj = new Main();

[Link](myObj.x);

ADVERTISEMENT

Multiple Objects
You can create multiple objects of one class:

Example
Create two objects of Main:
OOP WITH JAVA

public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj1 = new Main(); // Object 1

Main myObj2 = new Main(); // Object 2

[Link](myObj1.x);

[Link](myObj2.x);

Using Multiple Classes


You can also create an object of a class and access it in another class. This is often used
for better organization of classes (one class has all the attributes and methods, while the
other class holds the main() method (code to be executed)).

Remember that the name of the java file should match the class name. In this example,
we have created two files in the same directory/folder:

• [Link]
• [Link]

[Link]

public class Main {

int x = 5;
OOP WITH JAVA

[Link]

class Second {

public static void main(String[] args) {

Main myObj = new Main();

[Link](myObj.x);

When both files have been compiled:

C:\Users\Your Name>javac [Link]


C:\Users\Your Name>javac [Link]

Run the [Link] file:

C:\Users\Your Name>java Second

And the output will be:

You will learn much more about classes and objects in the next chapters.
OOP WITH JAVA

Java Class Attributes

Java Class Attributes


In the previous chapter, we used the term "variable" for x in the example (as shown
below). It is actually an attribute of the class. Or you could say that class attributes are
variables within a class:

ExampleGet your own Java Server


Create a class called "Main" with two attributes: x and y:

public class Main {

int x = 5;

int y = 3;

Another term for class attributes is fields.

Accessing Attributes
You can access attributes by creating an object of the class, and by using the dot syntax
(.):

The following example will create an object of the Main class, with the name myObj. We
use the x attribute on the object to print its value:

Example
Create an object called "myObj" and print the value of x:
OOP WITH JAVA

public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj = new Main();

[Link](myObj.x);

Modify Attributes
You can also modify attribute values:

Example
Set the value of x to 40:

public class Main {

int x;

public static void main(String[] args) {

Main myObj = new Main();

myObj.x = 40;

[Link](myObj.x);

}
OOP WITH JAVA

Or override existing values:

Example
Change the value of x to 25:

public class Main {

int x = 10;

public static void main(String[] args) {

Main myObj = new Main();

myObj.x = 25; // x is now 25

[Link](myObj.x);

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

Example
public class Main {

final int x = 10;

public static void main(String[] args) {

Main myObj = new Main();

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


a final variable
OOP WITH JAVA

[Link](myObj.x);

The final keyword is useful when you want a variable to always store the same value,
like PI (3.14159...).

The final keyword is called a "modifier". You will learn more about these in the Java
Modifiers Chapter.

ADVERTISEMENT

Multiple Objects
If you create multiple objects of one class, you can change the attribute values in one
object, without affecting the attribute values in the other:

Example
Change the value of x to 25 in myObj2, and leave x in myObj1 unchanged:

public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj1 = new Main(); // Object 1

Main myObj2 = new Main(); // Object 2

myObj2.x = 25;

[Link](myObj1.x); // Outputs 5
OOP WITH JAVA

[Link](myObj2.x); // Outputs 25

Multiple Attributes
You can specify as many attributes as you want:

Example
public class Main {

String fname = "John";

String lname = "Doe";

int age = 24;

public static void main(String[] args) {

Main myObj = new Main();

[Link]("Name: " + [Link] + " " + [Link]);

[Link]("Age: " + [Link]);

The next chapter will teach you how to create class methods and how to access them
with objects.
OOP WITH JAVA

Java Class Methods

Java Class Methods


You learned from the Java Methods chapter that methods are declared within a class,
and that they are used to perform certain actions:

ExampleGet your own Java Server


Create a method named myMethod() in Main:

public class Main {

static void myMethod() {

[Link]("Hello World!");

myMethod()prints a text (the action), when it is called. To call a method, write the
method's name followed by two parentheses () and a semicolon;

Example
Inside main, call myMethod():

public class Main {

static void myMethod() {

[Link]("Hello World!");

}
OOP WITH JAVA

public static void main(String[] args) {

myMethod();

// Outputs "Hello World!"

Static vs. Public


You will often see Java programs that have either static or public attributes and
methods.

In the example above, we created a static method, which means that it can be accessed
without creating an object of the class, unlike public, which can only be accessed by
objects:

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

public class Main {

// Static method

static void myStaticMethod() {

[Link]("Static methods can be called without creating


objects");

// Public method
OOP WITH JAVA

public void myPublicMethod() {

[Link]("Public methods must be called by creating


objects");

// Main method

public static void main(String[] args) {

myStaticMethod(); // Call the static method

// myPublicMethod(); This would compile an error

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

[Link](); // Call the public method on the object

Note: You will learn more about these keywords (called modifiers) in the Java
Modifiers chapter.

Access Methods With an Object


Example
Create a Car object named myCar. Call the fullThrottle() and speed() methods on
the myCar object, and run the program:

// Create a Main class


OOP WITH JAVA

public class Main {

// Create a fullThrottle() method

public void fullThrottle() {

[Link]("The car is going as fast as it can!");

// Create a speed() method and add a parameter

public void speed(int maxSpeed) {

[Link]("Max speed is: " + maxSpeed);

// Inside main, call the methods on the myCar object

public static void main(String[] args) {

Main myCar = new Main(); // Create a myCar object

[Link](); // Call the fullThrottle() method

[Link](200); // Call the speed() method

// The car is going as fast as it can!

// Max speed is: 200

Example explained
1) We created a custom Main class with the class keyword.
OOP WITH JAVA

2) We created the fullThrottle() and speed() methods in the Main class.

3) The fullThrottle() method and the speed() method will print out some text, when
they are called.

4) The speed() method accepts an int parameter called maxSpeed - we will use this in 8).

5) In order to use the Main class and its methods, we need to create an object of
the Main Class.

6) Then, go to the main() method, which you know by now is a built-in Java method that
runs your program (any code inside main is executed).

7) By using the new keyword we created an object with the name myCar.

8) Then, we call the fullThrottle() and speed() methods on the myCar object, and run
the program using the name of the object (myCar), followed by a dot (.), followed by the
name of the method (fullThrottle(); and speed(200);). Notice that we add
an int parameter of 200 inside the speed() method.

Remember that..
The dot (.) is used to access the object's attributes and methods.

To call a method in Java, write the method name followed by a set of parentheses (),
followed by a semicolon (;).

A class must have a matching filename (Main and [Link]).

ADVERTISEMENT

Using Multiple Classes


Like we specified in the Classes chapter, it is a good practice to create an object of a
class and access it in another class.
OOP WITH JAVA

Remember that the name of the java file should match the class name. In this example,
we have created two files in the same directory:

• [Link]
• [Link]

[Link]

public class Main {

public void fullThrottle() {

[Link]("The car is going as fast as it can!");

public void speed(int maxSpeed) {

[Link]("Max speed is: " + maxSpeed);

[Link]

class Second {

public static void main(String[] args) {

Main myCar = new Main(); // Create a myCar object

[Link](); // Call the fullThrottle() method

[Link](200); // Call the speed() method

When both files have been compiled:

C:\Users\Your Name>javac [Link]


C:\Users\Your Name>javac [Link]
OOP WITH JAVA

Run the [Link] file:

C:\Users\Your Name>java Second

And the output will be:

The car is going as fast as it can!


Max speed is: 200
OOP WITH JAVA

Java Constructors

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:

ExampleGet your own Java Server


Create a constructor:

// Create a Main class

public class Main {

int x; // Create a class attribute

// Create a class constructor for the Main class

public Main() {

x = 5; // Set the initial value for the class attribute x

public static void main(String[] args) {

Main myObj = new Main(); // Create an object of class Main (This


will call the constructor)

[Link](myObj.x); // Print the value of x

}
OOP WITH JAVA

// Outputs 5

Note that the constructor name must match the class name, and it cannot have
a return type (like void).

Also note that the constructor is called when the object is created.

All classes have constructors by default: if you do not create a class constructor yourself,
Java creates one for you. However, then you are not able to set initial values for object
attributes.

ADVERTISEMENT

Constructor Parameters
Constructors can also take parameters, which is used to initialize attributes.

The following example adds an int y parameter to the constructor. Inside the
constructor we set x to y (x=y). When we call the constructor, we pass a parameter to
the constructor (5), which will set the value of x to 5:

Example
public class Main {

int x;

public Main(int y) {

x = y;
OOP WITH JAVA

public static void main(String[] args) {

Main myObj = new Main(5);

[Link](myObj.x);

// Outputs 5

You can have as many parameters as you want:

Example
public class Main {

int modelYear;

String modelName;

public Main(int year, String name) {

modelYear = year;

modelName = name;

public static void main(String[] args) {

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

[Link]([Link] + " " + [Link]);


OOP WITH JAVA

// Outputs 1969 Mustang


OOP WITH JAVA

Java this

Java this Keyword


The this keyword in Java refers to the current object in a method or constructor.

The this keyword is often used to avoid confusion when class attributes have the same
name as method or constructor parameters.

Accessing Class Attributes


Sometimes a constructor or method has a parameter with the same name as a class
variable. When this happens, the parameter temporarily hides the class variable inside
that method or constructor.

To refer to the class variable and not the parameter, you can use the this keyword:

ExampleGet your own Java Server


public class Main {

int x; // Class variable x

// Constructor with one parameter x

public Main(int x) {

this.x = x; // refers to the class variable x

public static void main(String[] args) {


OOP WITH JAVA

// Create an object of Main and pass the value 5 to the


constructor

Main myObj = new Main(5);

[Link]("Value of x = " + myObj.x);

Output:
Value of x = 5

Tip: Think of this.x = x; as: "this.x (the class variable) gets the value of x (the
parameter)."

Without this, the code above x = x; would set the parameter x equal to itself, and the
class variable would stay uninitialized (0).

Calling a Constructor from Another


Constructor
You can also use this() to call another constructor in the same class.

This is useful when you want to provide default values or reuse initialization code
instead of repeating it.

Example
public class Main {

int modelYear;

String modelName;

// Constructor with one parameter


OOP WITH JAVA

public Main(String modelName) {

// Call the two-parameter constructor to reuse code and set a


default year

this(2020, modelName);

// Constructor with two parameters

public Main(int modelYear, String modelName) {

// Use 'this' to assign values to the class variables

[Link] = modelYear;

[Link] = modelName;

// Method to print car information

public void printInfo() {

[Link](modelYear + " " + modelName);

public static void main(String[] args) {

// Create a car with only model name (uses default year)

Main car1 = new Main("Corvette");

// Create a car with both model year and name

Main car2 = new Main(1969, "Mustang");


OOP WITH JAVA

[Link]();

[Link]();

Output:
2020 Corvette
1969 Mustang

Note: The call to this() must be the first statement inside the constructor.

When to use this?


• When a constructor or method has a parameter with the same name as a class
variable, use this to update the class variable correctly.
• To call another constructor in the same class and reuse code.
OOP WITH JAVA

Java Modifiers

Modifiers
By now, you are quite familiar with the public keyword that appears in almost all of our
examples:

public class Main

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
For classes, you can use either public or default:

Modifier Description

public The class is accessible by any other class


OOP WITH JAVA

default The class is only accessible by classes in the same package.

This is used 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

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. You

will learn more about packages in the Packages chapter

Protected The code is accessible in the same package and subclasses.

You will learn more about subclasses and superclasses in

the Inheritance chapter


OOP WITH JAVA

Public vs. Private Example


In the example below, the class has one public attribute and one private attribute.

Think of it like real life:

• public - a public park, everyone can enter


• private - your house key, only you can use it

ExampleGet your own Java Server


class Person {

public String name = "John"; // Public - accessible everywhere

private int age = 30; // Private - only accessible inside


this class

public class Main {

public static void main(String[] args) {

Person p = new Person();

[Link]([Link]); // Works fine

[Link]([Link]); // Error: age has private access in


Person

Example explained
Here, name is declared as public, so it can be accessed from outside the Person class.
But age is declared as private, so it can only be used inside the Person class.
OOP WITH JAVA

Java Non-Access Modifiers

Non-Access Modifiers
Non-access modifiers do not control visibility (like public or private), but instead
add other features to classes, methods, and attributes.

The most commonly used non-access modifiers are final, static, and abstract.

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

ExampleGet your own Java Server


public class Main {

final int x = 10;

final double PI = 3.14;

public static void main(String[] args) {

Main myObj = new Main();

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


a final variable

[Link] = 25; // will generate an error: cannot assign a value to


a final variable

[Link](myObj.x);
OOP WITH JAVA

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 Main {

// Static method

static void myStaticMethod() {

[Link]("Static methods can be called without creating


objects");

// Public method

public void myPublicMethod() {

[Link]("Public methods must be called by creating


objects");

// Main method
OOP WITH JAVA

public static void main(String[ ] args) {

myStaticMethod(); // Call the static method

// myPublicMethod(); This would output an error

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

[Link](); // Call the public method

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: [Link]

// abstract class
abstract class Main {

public String fname = "John";

public int age = 24;

public abstract void study(); // abstract method

// Subclass (inherit from Main)


OOP WITH JAVA

class Student extends Main {

public int graduationYear = 2018;

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


here

[Link]("Studying all day long");

// End code from filename: [Link]

// Code from filename: [Link]

class Second {

public static void main(String[] args) {

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


attributes and methods from Main)

Student myObj = new Student();

[Link]("Name: " + [Link]);

[Link]("Age: " + [Link]);

[Link]("Graduation Year: " + [Link]);

[Link](); // call abstract method


}

}
OOP WITH JAVA

Non-Access Modifiers List


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

abstract The class cannot be used to create objects (To access an abstract class, it must be inh
about 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

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
body is provided by the subclass (inherited from). You will learn more about inheritan

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

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 "ma
OOP WITH JAVA

Java Encapsulation

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:

ExampleGet your own Java Server


public class Person {

private String name; // private = restricted access

// Getter

public String getName() {

return name;
OOP WITH JAVA

// Setter

public void setName(String newName) {

[Link] = 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.

However, as the name variable is declared as private, we cannot access it from outside
this class:

Example
public class Main {

public static void main(String[] args) {

Person myObj = new Person();

[Link] = "John"; // error

[Link]([Link]); // error

If the variable was declared as public, we would expect the following output:
OOP WITH JAVA

John

However, as we try to access a private variable, we get an error:

[Link]: error: name has private access in Person


[Link] = "John";
^
[Link]: error: name has private access in Person
[Link]([Link]);
^
2 errors

Instead, we use the getName() and setName() methods to access and update the variable:

Example
public class Main {

public static void main(String[] args) {

Person myObj = new Person();

[Link]("John"); // Set the value of the name variable to


"John"

[Link]([Link]());

// Outputs "John"

Why Encapsulation?
• Better control of class attributes and methods
OOP WITH JAVA

• Class attributes can be made read-only (if you only use the get method),
or write-only (if you only use the set method)
• Flexible: the programmer can change one part of the code without affecting
other parts
• Increased security of data
OOP WITH JAVA

Java Packages

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: [Link]

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.

To use a class or a package from the library, you need to use the import keyword:

SyntaxGet your own Java Server


import [Link]; // Import a single class

import [Link].*; // Import the whole package


OOP WITH JAVA

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 [Link];

In the example above, [Link] is a package, while Scanner is a class of


the [Link] 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 [Link];

class Main {

public static void main(String[] args) {

Scanner myObj = new Scanner([Link]);

[Link]("Enter username");

String userName = [Link]();

[Link]("Username is: " + userName);

}
OOP WITH JAVA

ADVERTISEMENT

Import a Package
There are many packages to choose from. In the previous example, we used
the Scanner class from the [Link] 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 [Link] package:

Example
import [Link].*;

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
└── [Link]

To create a package, use the package keyword:

[Link]
package mypack;

class MyPackageClass {

public static void main(String[] args) {


OOP WITH JAVA

[Link]("This is my package!");

Save the file as [Link], and compile it:

C:\Users\Your Name>javac [Link]

Then compile the package:

C:\Users\Your Name>javac -d . [Link]

This forces the compiler to create the "mypack" package.

The -d keyword specifies the destination for where to save the class file. You can use any
directory name, like c:/user (windows), or, if you want to keep the package within the
same directory, you can use the dot sign ".", like in the example above.

Note: The package name should be written in lower case to avoid conflict with class
names.

When we compiled the package in the example above, a new folder was created, called
"mypack".

To run the [Link] file, write the following:

C:\Users\Your Name>java [Link]

The output will be:

This is my package!
OOP WITH JAVA

Java Inheritance

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

ExampleGet your own Java Server


class Vehicle {

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

public void honk() { // Vehicle method

[Link]("Tuut, tuut!");

class Car extends Vehicle {

private String modelName = "Mustang"; // Car attribute

public static void main(String[] args) {

// Create a myCar object


OOP WITH JAVA

Car myCar = new Car();

// Call the honk() method (from the Vehicle class) on the myCar
object

[Link]();

// Display the value of the brand attribute (from the Vehicle


class) and the value of the modelName from the Car class

[Link]([Link] + " " + [Link]);

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.

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.

ADVERTISEMENT

The final Keyword


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

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

final class Vehicle {

...

class Car extends Vehicle {

...

The output will be something like this:


[Link]: error: cannot inherit from final Vehicle
class Main extends Vehicle {
^
1 error)
OOP WITH JAVA

Java Polymorphism

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

ExampleGet your own Java Server


class Animal {

public void animalSound() {

[Link]("The animal makes a sound");

class Pig extends Animal {

public void animalSound() {

[Link]("The pig says: wee wee");

}
OOP WITH JAVA

class Dog extends Animal {

public void animalSound() {

[Link]("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() {

[Link]("The animal makes a sound");

class Pig extends Animal {

public void animalSound() {

[Link]("The pig says: wee wee");

class Dog extends Animal {

public void animalSound() {


OOP WITH JAVA

[Link]("The dog says: bow wow");

class Main {

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

[Link]();

[Link]();

[Link]();

Why And When To Use "Inheritance" and "Polymorphism"?

- It is useful for code reusability: reuse attributes and methods of an existing class when
you create a new class.
OOP WITH JAVA

Java super

Java super Keyword


In Java, the super keyword is used to refer to the parent class of a subclass.

The most common use of the super keyword is to eliminate the confusion between
superclasses and subclasses that have methods with the same name.

It can be used in two main ways:

• To access attributes and methods from the parent class


• To call the parent class constructor

Access Parent Methods


If a subclass has a method with the same name as one in its parent class, you can
use super to call the parent version:

ExampleGet your own Java Server


class Animal {

public void animalSound() {

[Link]("The animal makes a sound");

class Dog extends Animal {


OOP WITH JAVA

public void animalSound() {

[Link](); // Call the parent method

[Link]("The dog says: bow wow");

public class Main {

public static void main(String[] args) {

Dog myDog = new Dog();

[Link]();

Output:
The animal makes a sound
The dog says: bow wow

Note: Use super when you want to call a method from the parent class that has been
overridden in the child class.

Access Parent Attributes


You can also use super to access an attribute from the parent class if they have an
attribute with the same name:

Example
class Animal {

String type = "Animal";


OOP WITH JAVA

class Dog extends Animal {

String type = "Dog";

public void printType() {

[Link]([Link]); // Access parent attribute

public class Main {

public static void main(String[] args) {

Dog myDog = new Dog();

[Link]();

Output:
Animal

Call Parent Constructor


Use super() to call the constructor of the parent class. This is especially useful for
reusing initialization code.
OOP WITH JAVA

Example
class Animal {

Animal() {

[Link]("Animal is created");

class Dog extends Animal {

Dog() {

super(); // Call parent constructor

[Link]("Dog is created");

public class Main {

public static void main(String[] args) {

Dog myDog = new Dog();

Output:
Animal is created
Dog is created

Note: The call to super() must be the first statement in the subclass constructor.
OOP WITH JAVA

Java Inner Classes

Java Inner Classes


In Java, it is also possible to nest classes (a class within a class). The purpose of nested
classes is to group classes that belong together, which makes your code more readable
and maintainable.

To access the inner class, create an object of the outer class, and then create an object
of the inner class:

ExampleGet your own Java Server


class OuterClass {

int x = 10;

class InnerClass {

int y = 5;

public class Main {

public static void main(String[] args) {

OuterClass myOuter = new OuterClass();

[Link] myInner = [Link] InnerClass();

[Link](myInner.y + myOuter.x);

}
OOP WITH JAVA

// Outputs 15 (5 + 10)

Private Inner Class


Unlike a "regular" class, an inner class can be private or protected. If you don't want
outside objects to access the inner class, declare the class as private:

Example
class OuterClass {

int x = 10;

private class InnerClass {

int y = 5;

public class Main {

public static void main(String[] args) {

OuterClass myOuter = new OuterClass();

[Link] myInner = [Link] InnerClass();

[Link](myInner.y + myOuter.x);

}
OOP WITH JAVA

If you try to access a private inner class from an outside class, an error occurs:
[Link]: error: [Link] has private access in OuterClass
[Link] myInner = [Link] InnerClass();
^

ADVERTISEMENT

Static Inner Class


An inner class can also be static, which means that you can access it without creating
an object of the outer class:

Example
class OuterClass {

int x = 10;

static class InnerClass {

int y = 5;

public class Main {

public static void main(String[] args) {

[Link] myInner = new [Link]();


OOP WITH JAVA

[Link](myInner.y);

// Outputs 5

Note: just like static attributes and methods, a static inner class does not have access
to members of the outer class.

Access Outer Class From Inner Class


One advantage of inner classes, is that they can access attributes and methods of the
outer class:

Example
class OuterClass {

int x = 10;

class InnerClass {

public int myInnerMethod() {

return x;

public class Main {


OOP WITH JAVA

public static void main(String[] args) {

OuterClass myOuter = new OuterClass();

[Link] myInner = [Link] InnerClass();

[Link]([Link]());

// Outputs 10
OOP WITH JAVA

Java Abstraction

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

[Link]("Zzz");

From the example above, it is not possible to create an object of the Animal class:
OOP WITH JAVA

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:

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

ExampleGet your own Java Server


// Abstract class

abstract class Animal {

// Abstract method (does not have a body)

public abstract void animalSound();

// Regular method

public void sleep() {

[Link]("Zzz");

// Subclass (inherit from Animal)

class Pig extends Animal {

public void animalSound() {

// The body of animalSound() is provided here

[Link]("The pig says: wee wee");

class Main {
OOP WITH JAVA

public static void main(String[] args) {

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

[Link]();

[Link]();

Why And When To Use Abstract Classes and Methods?

To achieve security - hide certain details and only show the important details of an
object.

Note: Abstraction can also be achieved with Interfaces, which you will learn more about
in the next chapter.
OOP WITH JAVA

You might also like