[Go to site: main page, start]

0% found this document useful (0 votes)
4 views18 pages

Java Notes 2

The document provides an overview of key Java concepts including encapsulation, packages, inheritance, inner classes, abstract classes, interfaces, enums, and user input. It explains how encapsulation protects sensitive data, how to use packages for better organization, and the inheritance model in Java. Additionally, it covers the use of interfaces for abstraction, the characteristics of enums, and how to handle user input and dates in Java.

Uploaded by

Patrick Kilonzo
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)
4 views18 pages

Java Notes 2

The document provides an overview of key Java concepts including encapsulation, packages, inheritance, inner classes, abstract classes, interfaces, enums, and user input. It explains how encapsulation protects sensitive data, how to use packages for better organization, and the inheritance model in Java. Additionally, it covers the use of interfaces for abstraction, the characteristics of enums, and how to handle user input and dates in Java.

Uploaded by

Patrick Kilonzo
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 Notes

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


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:

public class Person {

private String name; // private = restricted access

// Getter

public String getName() {

return name;

// Setter

public void setName(String newName) {

[Link] = newName;

1
}

The this keyword is used to refer to the current object.

public class Main {

public static void main(String[] args) {

Person myObj = new Person();

[Link] = "John"; // error

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

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


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

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

2
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 & 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 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:

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

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

import [Link];

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

import [Link];

class MyClass {

public static void main(String[] args) {

Scanner myObj = new Scanner([Link]);

[Link]("Enter username");

String userName = [Link]();

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

• To import a whole package, end the sentence with an asterisk sign (*).
• To create a package, use the package keyword:

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.

4
In the example below, the Car class (subclass) inherits the attributes and
methods from the Vehicle class (superclass):

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

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

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

...

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

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

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:

class OuterClass {

int x = 10;

class InnerClass {

int y = 5;

7
}

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)

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:

class OuterClass {

int x = 10;

static class InnerClass {

int y = 5;

public class Main {

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

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

[Link](myInner.y);

// Outputs 5

Access Outer Class From Inner Class


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

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

9
}

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

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:

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

10
of extends). The body of the interface method is provided by the
"implement" class:

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

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

11
}

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:

interface FirstInterface {

public void myMethod(); // interface method

interface SecondInterface {

public void myOtherMethod(); // interface method

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

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

enum Level {

LOW,

MEDIUM,

HIGH

13
You can access enum constants with the dot syntax:

Level myVar = [Link];

• You can also have an enum inside a class:

public class Main {

enum Level {

LOW,

MEDIUM,

HIGH

public static void main(String[] args) {

Level myVar = [Link];

[Link](myVar);

enum Level {

LOW,

MEDIUM,

HIGH

public class Main {

public static void main(String[] args) {

14
Level myVar = [Link];

switch(myVar) {

case LOW:

[Link]("Low level");

break;

case MEDIUM:

[Link]("Medium level");

break;

case HIGH:

[Link]("High level");

break;

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

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

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

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

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

import [Link]; // import the LocalTime class

public class Main {

public static void main(String[] args) {

LocalTime myObj = [Link]();

[Link](myObj);

17
}

18

You might also like