UNIT-2 Java Programming Notes
UNIT-2 Java Programming Notes
UNIT-2
Java user defined Classes and Objects – Arrays – constructors - Inheritance: Basic concepts - Types of
inheritance - Member access rules - Usage of this and Super key word - Method Overloading -
Method overriding - Abstract classes - Dynamic method dispatch - Usage of final keyword -Packages:
Definition - Access Protection - Importing Packages - Interfaces: Definition – Implementation –
Extending Interfaces
Java Class
A Java classes is a blueprint or template used to create object. It serves as a fundamental building
block in Java programming, encapsulating data (fields) and behaviors (methods) into a single unit.
a Java class defines the structure and behavior of objects, serving as a blueprint for creating
instances of that class.
A Java class serves as a blueprint for creating objects and doesn’t take up memory.
It comprises variables of various types and methods. You can include data members,
methods, constructors, nested classes, and interfaces within a class.
It acts as a template for organizing and defining the behaviour of objects in your program.
package com.example;
import java.util.ArrayList;
this.age = age;
}
This syntax defines a class named MyClass in the com.example package, with a private
field age, a constructor that initializes age, and a method display() to print the age.
In Java, a class serves as a blueprint for creating objects. It encapsulates data and behavior
into a single unit. Here are the main components of a Java class:
Class Declaration: The class declaration defines the name of the class and any inheritance or
interfaces it implements.
// class body
Fields (Instance Variables): Fields represent the state or attributes of objects created from
the class.
Constructors: Constructors initialize objects of the class. They have the same name as the
class and are called when objects are created.
public MyClass(int age) {
this.age = age;
}
Methods define the behavior or actions that objects of the class can perfor
public void display() {
System.out.println("Age: " + age);
}
Access Modifiers: Access modifiers control the accessibility of class members (fields,
constructors, methods).
public class MyClass {
private int age;
public MyClass(int age)
this.age = age;
}
public void display() {
System.out.println("Age: " + age);
}
}
Built-in classes- The built-in classes are those which are pre-defined by the developers
in JDK.
Examples include-
java.util.Date
java.util.LinkedList
User-defined classes- So as the name suggests, user-defined classes are the classes created
by the user. We can add our functionality to the classes.
Java Objects
Syntax of an object
The syntax for creating an object in Java is:
ClassName objectName = new ClassName();
Car myCar = new Car();
Here, Car is the class name, myCar is the object name, and new
Car() instantiates a new object of the Car class.
Initializing an object
In Java, we can initialize objects in 3 ways-
By reference variable
By method
By constructor
By reference variable– Initialization of an object means storing the data in
the object. Let us understand this with an example-
public class MyClass {
public static void main(String[] args) {
// Initialize the object by reference variable in a single line
MyClass myObject = new MyClass();
Arrays in Java
What is an Array in Java?
An array refers to a data structure that contains homogeneous elements. This means that all
the elements in the array are of the same data type. Let's take an example:
1. Dynamic allocation: In arrays, the memory is created dynamically, which reduces the amount
of storage required for the code.
2. Elements stored under a single name: All the elements are stored under one name. This
name is used any time we use an array.
3. Occupies contiguous location: The elements in the arrays are stored at adjacent positions.
This makes it easy for the user to find the locations of its elements.
Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.
We have now declared a variable that holds an array of strings. To insert values to it, you can
place the values in a comma-separated list, inside curly braces:
Example:
Array Length
To find out how many elements an array has, use the length property:
Example
In this example, we have an array of five elements. They are stored in a single line or
adjacent memory locations.
Look at this example in Java code. Here, the five elements are 1, 2, 3, 4, and 5. We use a for
loop to print the elements of the array. The output of this is as follows:
2. Two-dimensional Array
Two-dimensional arrays store the data in rows and columns:
In this, the array has two rows and five columns. The index starts from 0,0 in the left-upper
corner to 1,4 in the right lower corner.
In this Java code, we have a two-dimensional array. We have two rows and three columns.
Brackets separate the rows, and the number of elements separates the columns. For this, we
use two for loops: one for rows and one for each element in the row. When we execute this
program, the result will be as follows:
3. Multi-dimensional Array
This is a combination of two or more arrays or nested arrays. We can even use more than
two rows and columns using the following code:
Here, we are using three rows and three columns, but we are only using two for loops.
Regardless of how many rows and columns are entered, the number of for loops will always
be two.
The above program will add all the elements defined in my_array[] and produce the result.
Constructors in Java
In Java, a Constructor is a block of codes similar to the method. It is called when an instance
of the class is created. At the time of calling the constructor, memory for the object is
allocated in the memory. It is a special type of method that is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is called.
Syntax
public class MyClass {
// Constructor
public MyClass() {
// Initialization code goes here
}
Parameterized Constructor
// Parameterized constructor
public MyClass(int intValue, String stringValue) {
myInt = intValue;
myString = stringValue;
}
In Java, constructors are similar to methods but without a return type. They can be
overloaded, just like methods, allowing for the creation of multiple constructors with
different parameter lists. Each constructor can serve a distinct purpose, with the compiler
distinguishing them based on the number and types of parameters they accept. This
technique, known as constructor overloading, enables flexibility in initializing objects based
on varying sets of input parameters.
class Dogs {
public Dogs() {
// No initialization parameters
}
public Dogs(String breed) {
this.breed = breed;
}
dog1.isRunning(0);
dog2.tailWagging("Woof");
// A dog with both name and breed initialized at the time of object creation.
Dogs dog3 = new Dogs("Snoopy", "German Shepherd");
}
}
Output:
Dog is not running
Dog is wagging its tail
A Copy Constructor in Java is used to create an object with the help of another object of the
same Java class.
The copy constructor has at least one object of the same class as an argument. The primary
objective of the copy constructor is to create a new object with the same properties as that
of the passed argument.
// Copy constructor
public MyClass(MyClass original) {
this.myInt = original.myInt;
this.myString = original.myString;
}
// Parameterized constructor
public MyClass(int intValue, String stringValue) {
this.myInt = intValue;
this.myString = stringValue;
}
System.out.println("nCopied Object:");
copiedObj.displayValues();
}
}
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):
class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}
}
// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand attribute (from the Vehicle class) and the value of the
modelName from the Car class
System.out.println(myCar.brand + " " + myCar.modelName);
}
}
1. Single-level inheritance
Single-level inheritance in Java is a fundamental concept where a subclass inherits from only
one superclass. This means that the subclass can acquire the properties and methods of the
superclass, enabling code reuse and the extension of existing functionality.
A graphical illustration of single-level inheritance is given below:
2. Multi-level Inheritance
Multilevel inheritance in Java is a feature that allows a class to inherit properties and
behaviours from another class, which in turn inherits from another class, forming a "chain"
of inheritance. This mechanism enables a class to inherit methods and fields from multiple
ancestors but in a direct line, where each class in the chain inherits from one class directly
above it.
3. Hierarchical Inheritance
Hierarchical inheritance in Java occurs when one base class (superclass) is inherited by
multiple subclasses. In this type of inheritance, all the features that are common in child
classes are included in the base class. This way, the code becomes more manageable and
reusable.
An interface in Java is a reference type, similar to a class, that can contain only constants,
method signatures, default methods, static methods, and nested types. Interfaces cannot
contain instance fields or constructor methods.
A class in Java can implement multiple interfaces, allowing it to inherit abstract methods
from multiple sources.
5. Hybrid Inheritance
Hybrid inheritance is a combination of two or more types of inheritance, such as
hierarchical, multiple, multilevel, or single inheritance. It integrates various inheritance
mechanisms to achieve a specific design or functionality
A graphical illustration of hybrid inheritance is given below:
Modifier Description
When methods, variables, classes, and so on are declared public, then we can access
them from anywhere. The public access modifier has no scope restriction.
// Animal.java file
// public class
public class Animal {
// public variable
public int legCount;
// public method
public void display() {
System.out.println("I am an animal.");
System.out.println("I have " + legCount + " legs.");
}
}
// Main.java
public class Main {
public static void main( String[] args ) {
// accessing the public class
Animal animal = new Animal();
Output:
I am an animal.
I have 4 legs.
When variables and methods are declared private, they cannot be accessed outside
of the class.
For example,
class Data {
// private variable
private String name;
}
public class Main {
public static void main(String[] main){
Output:
The name is Programiz
When methods and data members are declared protected, we can access them
within the same package as well as from subclasses.
For example,
class Animal {
// protected method
protected void display() {
System.out.println("I am an animal");
}
}
Output:
I am an animal
Default Access Modifier
If we do not explicitly specify any access modifier for classes, methods, variables, etc,
then by default the default access modifier is considered.
package defaultPackage;
class Logger {
void message(){
System.out.println("This is a message");
}
}
Access Parent Class Variables: When a child class has a variable with the same name
as its parent class, super helps access the parent’s variable.
Call Parent Class Methods: If a child class overrides a method from its parent, super
allows calling the parent class’s version of the method.
Invoke Parent Class Constructor: super() can be used to call the parent class
constructor from a child class constructor.
Differentiate Between Parent and Child Class Members: It helps when both parent
and child classes have members with the same name.
Improve Code Reusability: By using super, we can reuse parent class functionalities
instead of rewriting code in the child class.
Syntax
super();
super.methodName();
super.fieldName;
In this example, the super() call in the Dog constructor invokes the
constructor of the Animal class.
Example 1: Calling Superclass Constructor
class Animal {
class Animal {
Animal() {
System.out.println("Animal constructor called");
}
}
Here, the super.sound() call in the Dog class method sound() invokes
the sound() method of the Animal class.
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Animal {
String color = "white";
}
class Dog extends Animal {
String color = "black";
void displayColor() {
System.out.println("Dog color: " +// Prints the color of Dog class
System.out.println("Animal color: " + super.// Prints the color of
Animal class
}
}
public class TestSuper {
public static void main(String[] args) {
Dog d = new Dog();
d.displayColor(); // Output: Dog color: black
// Animal color: white
}
this keyword
this keyword:
It is a reserved keyword in Java that is used to refer to the current class object. It is a
reference variable through which the method is called. Other uses of this keyword
are:
o We can use it to refer current class instance variable.
o We can use it to invoke the current class method (implicitly).
o We can pass it as an argument in the method and constructor calls.
o We can also use it for returning the current class instance from the method.
this super
The current instance of the class is The current instance of the parent class is
represented by this keyword. represented by the super keyword.
In order to call the default constructor of the In order to call the default constructor of the
current class, we can use this keyword. parent class, we can use the super keyword.
It can be referred to from a static context. It It can't be referred to from a static context. It
means it can be invoked from the static means it cannot be invoked from a static
context. context.
We can use it to access only the current class We can use it to access the data members and
data members and member functions. member functions of the parent class.
The method is superclass and overridden method in the subclass should have the same declaration
signature such as parameters list, type, and return type.
Usage of Java Method Overriding
Method overriding is used for writing specific definition of a subclass method (this method is
known as the overridden method).
The argument list should be exactly the same as that of the overridden method.
The return type should be the same or a subtype of the return type declared in the original
overridden method in the superclass.
The access level cannot be more restrictive than the overridden method's access level. For
example: If the superclass method is declared public then the overridding method in the sub
class cannot be either private or protected.
Instance methods can be overridden only if they are inherited by the subclass.
A subclass within the same package as the instance's superclass can override any superclass
method that is not declared private or final.
A subclass in a different package can only override the non-final methods declared public or
protected.
An overriding method can throw any uncheck exceptions, regardless of whether the
overridden method throws exceptions or not. However, the overriding method should not
throw checked exceptions that are new or broader than the ones declared by the overridden
method. The overriding method can throw narrower or fewer exceptions than the
overridden method.
class Animal {
public void move()
super.move();
b.move();
Output
class MethodOverloading {
display(1);
display(1, 4);
Output:
Arguments: 1
Arguments: 1 and 4
class MethodOverloading {
display(1);
display("Hello");
Output:
Here, both overloaded methods accept one argument. However, one accepts the argument of
type int whereas other accepts String object.
Important Points
Two or more methods can have the same name inside the same class if they accept different
arguments. This feature is known as method overloading.
It is not method overloading if we only change the return type of methods. There must be
differences in the number of parameters.
Difference between method overloading and method overriding:
Java Abstraction
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).
System.out.println("Zzz");
Java Polymorphism
Polymorphism in Java is a core concept of object-oriented programming (OOP) that allows objects to
be treated as instances of their parent class. It facilitates flexibility and the ability to define methods
in multiple forms. Polymorphism is primarily achieved through method overriding and method
overloading.
Usage
Polymorphism is used to perform a single action in different ways. It allows for the implementation
of dynamic method dispatch, where the method to be executed is determined at runtime. This is
beneficial for implementing a cleaner and more maintainable codebase.
Types of Polymorphism
1. Compile-time Polymorphism (Method Overloading): Achieved by defining multiple methods
with the same name but different parameters within the same class.
Examples
return a + b;
return a + b;
}
In this example, the add method is overloaded with two different parameter lists. The appropriate
method is called based on the arguments passed.
class Animal {
@Override
System.out.println("Dog barks");
Here, the Dog class overrides the sound method of the Animal class. The sound method of
the Dog class is invoked at runtime.
final Keyword in Java
The final keyword in Java is a non-access modifier that can be applied to variables, methods, and
classes. It is used to restrict the user from further modifying the entity to which it is applied. This
keyword plays a crucial role in ensuring immutability and preventing inheritance or method
overriding.
Usage:
1. final Variables
public FinalInitialization() {
MAX_VALUE = 100;
Examples
}
2. final Methods
A final method cannot be overridden by subclasses, ensuring that the method's implementation
remains unchanged.
class Parent {
class Parent {
// System.out.println("Attempting to override.");
// }
obj.display();
3. final Classes
// Class implementation
// }
obj.show();
Packages in Java
A Java package is a group of similar types of classes, interfaces and sub-packages.
Organise Classes: For organizing the class, interfaces and other components, packages are used.
o Control Access: It is the package that controls the access of the protected and default
members. Think what would be the use of default and protected access specifiers if packages
were absent?
o Reusability: Java enhances the reusability management of code and does the promotion of
data encapsulation with the help of packages.
Types of Packages
1. Built-in Packages
2. User-defined Packages
1.Built-in Packages
Some of the built-in packages that are used commonly are:
java.lang: It contains those classes that are required for language support, such as classes for
primitive data types and math operations. This package is automatically imported into Java.
java.io: It contains all those classes that are required for the input/output operations.
java.util: It contains utility classes that are needed for the data structures, such as Array, List, Map,
etc.
java.applet: All those classes that are required for finding applets are found in this package.
java.awt: It contains all those classes that are required for creating components of GUI (Graphical
User Interface).
java.net: It includes classes that are used for doing tasks in the field of networking.
2.User-defined Packages
In this section, we will create two Java files in two different packages (or folders). We will also create
three files. One file each for both the folders, and the last file is of the main class.
To create a package in Java, you use the `package` keyword. The package statement must be the first
line in the source file (excluding comments).
Creating a Package:
// File: com/example/HelloWorld.java
package com.example;
In this example:
- The `package com.example;` statement defines that the class `HelloWorld` belongs to the
`com.example` package.
To access a class from a package, the fully qualified name of the class (including the package name)
should be used, or the class should be imported.
6. Importing Packages
import com.example.HelloWorld;
import com.example.*;
In the second example, all classes within the `com.example` package will be imported.
7. Sub-packages in Java
Java supports sub-packages, which are simply packages within other packages. There is no special
syntax for sub-packages; they are treated like regular packages, but the hierarchy is created by
adding dots in the package name.
Example:
package com.example.utils;
Java follows certain conventions for naming packages to ensure uniqueness and clarity:
1. Reverse Domain Name: Use your domain name in reverse as the base of your package names. For
example, if your domain is `example.com`, start your package with `com.example`.
2. Lowercase Names: Use lowercase letters to avoid conflicts with class names.
3. Meaningful Names: Use descriptive and meaningful names to reflect the content of the package.
Java comes with several built-in packages that provide a wide range of functionalities. Some common
built-in packages are:
- java.util: Contains utility classes, including collections framework, date, time facilities, and more.
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:
Example
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}
Relationship Between Class and Interface
A class can extend another class, and similarly, an interface can extend another interface.
However, only a class can implement an interface, and the reverse (an interface
implementing a class) is not allowed.
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
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
}
class Main {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}