0% found this document useful (0 votes)
2 views59 pages

Java Class Objects

The document provides an overview of Object-Oriented Programming (OOP) in Java, explaining key concepts such as classes, objects, attributes, and methods. It highlights the advantages of OOP, including faster execution, better code organization, and reusability. Additionally, it covers the use of constructors, the 'this' keyword, and provides coding examples to illustrate these concepts.

Uploaded by

ekumeewane96
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)
2 views59 pages

Java Class Objects

The document provides an overview of Object-Oriented Programming (OOP) in Java, explaining key concepts such as classes, objects, attributes, and methods. It highlights the advantages of OOP, including faster execution, better code organization, and reusability. Additionally, it covers the use of constructors, the 'this' keyword, and provides coding examples to illustrate these concepts.

Uploaded by

ekumeewane96
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

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:

class
Fruit

objects
Apple

Banana

Mango
Another example:

class
Car

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

You will learn much more about classes and objects in the next chapter.

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.

In this example, we create a class named "Main" with a variable x:

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

2
In Java, an object is created from a class. After defining a class, you can create objects
from it using the new keyword:

ExampleGet your own Java Server


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

Multiple Objects
You can create multiple objects of one class:

Example
Create two objects of Main:

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 {
3
int x = 5;
}

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

Java Class Attributes


Java Class Attributes
In the previous chapter, we used the term "variable" for x in the example (as shown
below).
In Java, variables declared inside a class are called "attributes".
You can also say that attributes are variables that belong to a class:
Create a class called "Main" with two attributes: x and y:
public class Main {
int x = 5;
int y = 3;
}
Another name for attributes is fields.

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

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

ExampleGet your own Java Server


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

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

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

5
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
[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.

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
[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";
6
int age = 24;

public static void main(String[] args) {


Main myObj = new Main();
[Link]("Name: " + [Link] + " " + [Link]);
[Link]("Age: " + [Link]);
}
}

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:

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;

ExampleGet your own Java Server


Inside main, call myMethod():
public class Main {
static void myMethod() {
[Link]("Hello World!");
}

public static void main(String[] args) {


myMethod();
}
}
// Outputs "Hello World!"

Access Methods With an Object


Example

7
Create a Car object named myCar. Call the fullThrottle() and speed() methods on
the myCar object, and run the program:
// Create a Main class
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.
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]).
8
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.

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]
[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);
}
}
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:
The car is going as fast as it can!
Max speed is: 200

Java Class Code Challenge


Challenge: Create a Person Object
Test your understanding of Java Classes and Objects by completing a small coding
challenge.

Instructions
Inside the Main class, complete the following steps:
1. Create a String variable named city and set it to "London"
2. Create an int variable named population and set it to 9000000
3. Inside main(), create an object of Main named myObj
4. Print city and population using myObj

9
public class Main {
// Create a String variable
// Create an int variable
public static void main(String[] args) {
// Create a Main object
// Print city the object
// Print population using the object
}
}

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


10
Main myObj = new Main(); // Create an object of class Main (This
will call the constructor)

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

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

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;
}

public static void main(String[] args) {


Main myObj = new Main(5);
[Link](myObj.x);
}
}

// Outputs 5

11
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]);
}
}

// Outputs 1969 Mustang

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

12
}

public static void main(String[] args) {


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


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

[Link]();

[Link]();
}
}
Output:
2020 Corvette
1969 Mustang
Note: The call to this() must be the first statement inside the constructor.

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 Try


it

public The class is accessible by any other class

14
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 Try it

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

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

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
16
[Link] = 25; // will generate an error: cannot assign a value
to a final variable

[Link](myObj.x);

Static
A static method belongs to the class, not to any specific object. This means you
can call it without creating an object of the class.

Example
A simple example showing how to call a static method directly:

public class Main {

// Static method

static void myStaticMethod() {

[Link]("Static methods can be called without


creating objects");

// Main method

public static void main(String[] args) {

myStaticMethod(); // Call the static method

[Link](); // Or call it using the class name

17
Note: A static method belongs to the class itself. You can call it without creating
an object, but it cannot use variables or methods that belong to an object.

REMOVE ADS

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

[Link]
[Link]

// abstract class
abstract class Main {

public String fname = "John";

public int age = 24;

public abstract void study(); // abstract method

// Subclass (inherit from Main)

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

18
Non-Access Modifiers List
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 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 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 belong to the class, not to objects. This means all objects
share the same static attribute, and static methods can be called without
creating objects.

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

19
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"

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


20
public class Person {

private String name; // private = restricted access

// Getter

public String getName() {

return name;

// 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
21
}

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

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"

REMOVE ADS

22
Why Encapsulation?
 Better control of class attributes and methods
 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

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


23
import [Link]; // Import a single class

import [Link].*; // 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 [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);

24
REMOVE ADS

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

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

}
25
}

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!

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.

26
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

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?


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

REMOVE ADS

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 {

...

The output will be something like this:


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

Java Polymorphism
28
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");

class Dog extends Animal {

public void animalSound() {

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

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

[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

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

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 {

31
public void animalSound() {

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

class Dog extends Animal {

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:

32
Example
class Animal {

String type = "Animal";

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.

Example
33
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.

Java Inner Classes

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

// Outputs 15 (5 + 10)

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

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

REMOVE ADS

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

[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


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

public static void main(String[] args) {

OuterClass myOuter = new OuterClass();

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

[Link]([Link]());

// Outputs 10

Java Abstraction

Abstract Classes and Methods


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

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

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

public static void main(String[] args) {

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

[Link]();

[Link]();

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

Java Interface

Interfaces
Another way to achieve abstraction in Java, is with interfaces.

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


with empty bodies:

ExampleGet your own Java Server


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

Example
// Interface

interface Animal {

41
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

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

public void sleep() {

// The body of sleep() is provided here

[Link]("Zzz");

class Main {

public static void main(String[] args) {

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

[Link]();

[Link]();

Notes on Interfaces:

42
 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).

REMOVE ADS

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

Example
interface FirstInterface {

public void myMethod(); // interface method

interface SecondInterface {

public void myOtherMethod(); // interface method

43
class DemoClass implements FirstInterface, SecondInterface {

public void myMethod() {

[Link]("Some text..");

public void myOtherMethod() {

[Link]("Some other text...");

class Main {

public static void main(String[] args) {

DemoClass myObj = new DemoClass();

[Link]();

[Link]();

Java Anonymous Class

Anonymous Class
An anonymous class is a class without a name. It is created and used at the same
time.

You often use anonymous classes to override methods of an existing class or


interface, without writing a separate class file.

Here, we create an anonymous class that extends another class and overrides its
method:
44
// Normal class

class Animal {

public void makeSound() {

[Link]("Animal sound");

public class Main {

public static void main(String[] args) {

// Anonymous class that overrides makeSound()

Animal myAnimal = new Animal() {

public void makeSound() {

[Link]("Woof woof");

}; // semicolon is required to end the line of code that creates


the object

[Link]();

The output will be:

Woof woof

Anonymous Class from an Interface


You can also use an anonymous class to implement an interface on the fly:

// Interface

45
interface Greeting {

void sayHello();

public class Main {

public static void main(String[] args) {

// Anonymous class that implements Greeting

Greeting greet = new Greeting() {

public void sayHello() {

[Link]("Hello, World!");

};

[Link]();

The output will be:

Hello, World!

When to Use Anonymous Classes?


Use anonymous classes when you need to create a short class for one-time use. For
example:

 Overriding a method without creating a new subclass


 Implementing an interface quickly
 Passing small pieces of behavior as objects

Java Enums
46
Enums
An enum is a special "class" that represents a group of constants (unchangeable
variables, like final variables).

To create an enum, use the enum keyword (instead of class or interface), and separate
the constants with a comma. Note that they should be in uppercase letters:

ExampleGet your own Java Server


enum Level {

LOW,

MEDIUM,

HIGH

You can access enum constants with the dot syntax:

Level myVar = [Link];

Enum is short for "enumerations", which means "specifically listed".

Enum inside a Class


You can also have an enum inside a class:

Example
public class Main {

enum Level {

LOW,

MEDIUM,

HIGH

}
47
public static void main(String[] args) {

Level myVar = [Link];

[Link](myVar);

The output will be:

MEDIUM

Enum in a Switch Statement


Enums are often used in switch statements to check for corresponding values:

Example
enum Level {

LOW,

MEDIUM,

HIGH

public class Main {

public static void main(String[] args) {

Level myVar = [Link];

switch(myVar) {

case LOW:

[Link]("Low level");

break;
48
case MEDIUM:

[Link]("Medium level");

break;

case HIGH:

[Link]("High level");

break;

The output will be:

Medium level

Loop Through an Enum


The enum type has a values() method, which returns an array of all enum constants.
This method is useful when you want to loop through the constants of an enum:

Example
for (Level myVar : [Link]()) {

[Link](myVar);

The output will be:


LOW
MEDIUM
HIGH

Difference between Enums and Classes


An enum can, just like a class, have attributes and methods. The only difference is that
enum constants are public, static and final (unchangeable - cannot be overridden).

An enum cannot be used to create objects, and it cannot extend other classes (but it
can implement interfaces).
49
Why And When To Use Enums?
Use enums when you have values that you know aren't going to change, like month
days, days, colors, deck of cards, etc.

Java Enum Constructor

Enum Constructor
An enum can also have a constructor just like a class.

The constructor is called automatically when the constants are created. You cannot
call it yourself.

Here, each constant in the enum has a value (a string) that is set through the
constructor:

enum Level {

// Enum constants (each has its own description)

LOW("Low level"),

MEDIUM("Medium level"),

HIGH("High level");

// Field (variable) to store the description text

private String description;

// Constructor (runs once for each constant above)

private Level(String description) {

[Link] = description;

50
// Getter method to read the description

public String getDescription() {

return description;

public class Main {

public static void main(String[] args) {

Level myVar = [Link]; // Pick one enum constant

[Link]([Link]()); // Prints "Medium


level"

The output will be:


Medium level

Note: The constructor for an enum must be private. If you don't write private, Java
adds it automatically.

Loop Through Enum with Constructor


You can also loop through the constants and print their values using
the values() method:

for (Level myVar : [Link]()) {

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

The output will be:


LOW: Low level
MEDIUM: Medium level
HIGH: High level

51
Java User Input (Scanner)

Java User Input


The Scanner class is used to get user input, and it is found in
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 Strings:

ExampleGet your own Java Server


import [Link]; // Import the Scanner class

class Main {

public static void main(String[] args) {

Scanner myObj = new Scanner([Link]); // Create a Scanner


object

[Link]("Enter username");

String userName = [Link](); // Read user input

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


input

If you don't know what a package is, read our Java Packages Tutorial.

52
Input Types
In the example above, we used the nextLine() method, which is used to read
Strings. To read other types, look at the table below:

Method Description

nextBoolean() Reads a boolean value from the user

nextByte() Reads a byte value from the user

nextDouble() Reads a double value from the user

nextFloat() Reads a float value from the user

nextInt() Reads a int value from the user

nextLine() Reads a String value from the user

nextLong() Reads a long value from the user

nextShort() Reads a short value from the user

In the example below, we use different methods to read data of various types:

Example
import [Link];

53
class Main {

public static void main(String[] args) {

Scanner myObj = new Scanner([Link]);

[Link]("Enter name, age and salary:");

// String input

String name = [Link]();

// Numerical input

int age = [Link]();

double salary = [Link]();

// Output input by user

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

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

[Link]("Salary: " + salary);

Note: If you enter wrong input (e.g. text in a numerical input), you will get an
exception/error message (like "InputMismatchException").

You can read more about exceptions and how to handle errors in the Exceptions
chapter.

REMOVE ADS

54
Complete Scanner Reference
Tip: For a complete reference of Scanner methods, go to our Java Scanner Reference.

Java Date and Time

Java Dates
Java does not have a built-in Date class, but we can import the [Link] package
to work with the date and time API. The package includes many date and time
classes. For example:

Class Description

LocalDate Represents a date (year, month, day (yyyy-MM-dd))

LocalTime Represents a time (hour, minute, second and nanoseconds (HH-mm

LocalDateTime Represents both a date and a time (yyyy-MM-dd-HH-mm-ss-ns)

DateTimeFormatter Formatter for displaying and parsing date-time objects

If you don't know what a package is, read our Java Packages Tutorial.

Display Current Date


To display the current date, import the [Link] class, and use
its now() method:

55
ExampleGet your own Java Server
import [Link]; // import the LocalDate class

public class Main {

public static void main(String[] args) {

LocalDate myObj = [Link](); // Create a date object

[Link](myObj); // Display the current date

The output will be:

2026-05-23

Display Current Time


To display the current time (hour, minute, second, and nanoseconds), import
the [Link] class, and use its now() method:

Example
import [Link]; // import the LocalTime class

public class Main {

public static void main(String[] args) {

LocalTime myObj = [Link]();

[Link](myObj);

This example displays the server's local time, which may differ from your local time:

56
1:11:36.652986

Display Current Date and Time


To display the current date and time, import the [Link] class,
and use its now() method:

Example
import [Link]; // import the LocalDateTime class

public class Main {

public static void main(String[] args) {

LocalDateTime myObj = [Link]();

[Link](myObj);

The output will be something like this:

2026-05-23T01:11:36.652255

Formatting Date and Time


The "T" in the example above is used to separate the date from the time. You can use
the DateTimeFormatter class with the ofPattern() method in the same package
to format or parse date-time objects. The following example will remove both the "T"
and nanoseconds from the date-time:

Example
import [Link]; // Import the LocalDateTime class

import [Link]; // Import the


DateTimeFormatter class

57
public class Main {

public static void main(String[] args) {

LocalDateTime myDateObj = [Link]();

[Link]("Before formatting: " + myDateObj);

DateTimeFormatter myFormatObj = [Link]("dd-


MM-yyyy HH:mm:ss");

String formattedDate = [Link](myFormatObj);

[Link]("After formatting: " + formattedDate);

The output will be:

Before Formatting: 2026-05-23T01:11:36.682487


After Formatting: 23-05-2026 01:11:36

The ofPattern() method accepts all sorts of values, if you want to display the date
and time in a different format. For example:

Value Example Tryit

yyyy-MM-dd "1988-09-29"

dd/MM/yyyy "29/09/1988"

58
dd-MMM-yyyy "29-Sep-1988"

E, MMM dd yyyy "Thu, Sep 29 1988"

59

You might also like