Java Class
Java Class
Java Class
Java Class
A class is a blueprint for the object. Before we create an
object, we first need to define the class.
We can think of the class as a sketch (prototype) of a
house. It contains all the details about the floors, doors,
windows, etc. Based on these descriptions we build the
house. House is the object.
Since many houses can be made from the same
description, we can create many objects from a class.
Create a class in Java
We can create a class in Java using the class keyword.
For example,
class ClassName {
// fields
// methods
}
Here, fields (variables) and methods represent
the state and behavior of the object respectively.
• fields are used to store data
• methods are used to perform some operations
For our bicycle object, we can create the class as
class Bicycle {
// state or field
private int gear = 5;
// behavior or method
public void braking() {
System.out.println("Working of Braking");
}
}
Java Objects
An object is called an instance of a class. For example,
suppose Bicycle is a class
then MountainBicycle, SportsBicycle, TouringBicyc
le, etc can be considered as objects of the class.
Creating an Object in Java
Here is how we can create an object of a class.
// field of class
int gear = 5;
// method of class
void braking() {
...
}
}
// create object
Bicycle sportsBicycle = new Bicycle();
Java Constructors
What is a Constructor?
A constructor in Java is similar to a method that is invoked
when an object of the class is created.
Unlike Java methods, a constructor has the same name
as that of the class and does not have any return type. For
example,
class Test {
Test() {
// constructor body
}
}
class Main {
private String name;
// constructor
Main() {
System.out.println("Constructor Called:");
name = "Programiz";
}
Output:
Constructor Called:
The name is Programiz
private Constructor() {
// body of the constructor
}
class Main {
int i;
Output:
Constructor is called
Value of i: 5
class Company {
String name;
// public constructor
public Company() {
name = "Programiz";
}
}
class Main {
public static void main(String[] args) {
Output:
Company name = Programiz
class Main {
String languages;
Output:
Java Programming Language
Python Programming Language
C Programming Language
class Main {
int a;
boolean b;
System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}
Output:
a = 0
b = false
Here, we haven't created any constructors. Hence, the
Java compiler automatically creates the default
constructor.
The default constructor initializes any uninitialized instance
variables with default values.
Type Default Value
boolean false
byte 0
short 0
int 0
long 0L
char \u0000
float 0.0f
double 0.0d
class Main {
int a;
boolean b;
// a private constructor
private Main() {
a = 0;
b = false;
}
System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}
class Main {
String language;
obj1.getName();
obj2.getName();
}
}
Output:
Programming Language: Java
Programming Language: Python
For example:
void func() { ... }
void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }
Output:
Arguments: 1
Arguments: 1 and 4
Output:
Got Integer data.
Got String object.
Here, both overloaded methods accept one argument.
However, one accepts the argument of type intwhereas
other accepts Stringobject.
System.out.println(hs.formatNumber(500));
System.out.println(hs.formatNumber(89.9934));
System.out.println(hs.formatNumber("550"));
}
}
500
89.993
550.00
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.
• Method overloading is achieved by either:
o changing the number of arguments.
o or changing the data type of arguments.
• It is not method overloading if we only change the return
type of methods. There must be differences in the number
of parameters
class Test {
// static method inside the Test class
public static void method() {...}
}
class Main {
// invoking the static method
Test.method();
}
class StaticTest {
// non-static method
int multiply(int a, int b){
return a * b;
}
// static method
static int add(int a, int b){
return a + b;
}
}
Output:
2 * 2 = 4
2 + 3 = 5
Static Variables
In Java, when we create objects of a class, then every
object will have its own copy of all the variables of the
class. For example,
class Test {
// regular variable
int age;
}
class Main {
// create instances of Test
Test test1 = new Test();
Test test2 = new Test();
}
Here, both the objects test1 and test2 will have separate
copies of the variable age. And, they are different from
each other.
However, if we declare a variable static, all objects of the
class share the same static variable. It is because like
static methods, static variables are also associated with
the class. And, we don't need to create objects of the class
to access the static variables. For example,
class Test {
// static variable
static int age;
}
class Main {
// access the static variable
Test.age = 20;
}
class Test {
// static variable
static int max = 10;
// non-static variable
int min = 5;
}
Output:
min + 1 = 6
max + 1 = 11
// static variable
static int age;
// static method
static void display() {
System.out.println("Static Method");
}
public static void main(String[] args) {
Output:
Age is 30
Static Method
Static Blocks
In Java, static blocks are used to initialize the static
variables. For example,
class Test {
// static variable
static int age;
// static block
static {
age = 23;
}
}
Here we can see that we have used a static block with the
syntax:
static {
// variable initialization
}
class Main {
// static variables
static int a = 23;
static int b;
static int max;
// static blocks
static {
System.out.println("First Static
block.");
b = a * 4;
}
static {
System.out.println("Second Static
block.");
max = 30;
}
// static method
static void display() {
Output:
First Static block.
Second Static block.
a = 23
b = 92
max = 30
Java Inheritance
class Animal {
class Main {
public static void main(String[] args) {
}
}
Output
My name is Rohu
I can eat
labrador.eat();
Here, labrador is an object of Dog.
However, name and eat() are the members of
the Animal class.
Since Dog inherits the field and method from Animal, we
are able to access the field and method using the object of
the Dog.
Java
Inheritance Implementation
is-a relationship
In Java, inheritance is an is-arelationship. That is, we use
inheritance only if there exists an is-a relationship between
two classes. For example,
• Car is a Vehicle
• Orange is a Fruit
• Surgeon is a Doctor
• Dog is an Animal
Here, Car can inherit from Vehicle, Orange can inherit
from Fruit, and so on.
class Animal {
class Main {
public static void main(String[] args) {
Output
I eat dog food
I can bark
In the above example, the eat()method is present in both
the superclass Animal and the subclass Dog.
Here, we have created an object labrador of Dog.
Now when we call eat() using the object labrador, the
method inside Dog is called. This is because the method
inside the derived class overrides the method inside the
base class.
This is called method overriding. To learn more, visit Java
Method Overriding.
Note: We have used the @Override annotation to tell the
compiler that we are overriding a method. However, the
annotation is not mandatory. To learn more, visit Java
Annotations.
class Animal {
Output
I can eat
I eat dog food
I can bark
In the above example, the eat()method is present in both
the base class Animal and the derived class Dog. Notice
the statement,
super.eat();
Here, the super keyword is used to call the eat() method
present in the superclass.
We can also use the super keyword to call the constructor
of the superclass from the constructor of the subclass. To
learn more, visit Java super keyword.
protected Members in Inheritance
In Java, if a class includes protected fields and methods,
then these fields and methods are accessible from the
subclass of the class.
Example 4: protected Members in Inheritance
class Animal {
protected String name;
class Main {
public static void main(String[] args) {
labrador.getInfo();
}
}
Output
I am an animal.
My name is Rocky
Types of inheritance
There are five types of inheritance.
1. Single Inheritance
In single inheritance, a single subclass extends from a
single superclass. For example,
3. Hierarchical Inheritance
In hierarchical inheritance, multiple subclasses extend
from a single superclass. For example,
Java Hierarchical
Inheritance
4. Multiple Inheritance
In multiple inheritance, a single subclass extends from
multiple superclasses. For example,
Java Multiple
Inheritance
Note: Java doesn't support multiple inheritance. However,
we can achieve multiple inheritance using interfaces. To
learn more, visit Java implements multiple inheritance.
5. Hybrid Inheritance
Hybrid inheritance is a combination of two or more types
of inheritance. For example,
class Main {
public static void main(String[] args) {
Java Arrays
Here, the above array cannot store more than 100 names.
The number of values in a Java array is always fixed.
dataType[] arrayName;
• dataType - it can be primitive data
types like int, char, double, byte, etc. or Java objects
• arrayName - it is an identifier
For example,
double[] data;
Here, data is an array that can hold values of
type double.
But, how many elements can array this hold?
Good question! To define the number of elements that an
array can hold, we have to allocate memory for the array
in Java. For example,
// declare an array
double[] data;
// allocate memory
data = new double[10];
// declare an array
int[] age = new int[5];
// initialize array
age[0] = 12;
age[1] = 4;
age[2] = 5;
..
Note:
• Array indices always start from 0. That is, the first element
of an array is at index 0.
• If the size of an array is n, then the last element of the
array will be at index n-1.
How to Access Elements of an Array in Java?
We can access the element of an array using the index
number. Here is the syntax for accessing elements of an
array,
class Main {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5, 2, 5};
Output
Accessing Elements of Array:
First Element: 12
Second Element: 4
Third Element: 5
Fourth Element: 2
Fifth Element: 5
class Main {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5};
Output
Using for Loop:
12
4
5
class Main {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5};
Output
Using for-each Loop:
12
4
5
class Main {
public static void main(String[] args) {
Output:
Sum = 36
Average = 3.6
In the above example, we have created an array of
named numbers. We have used the for...each loop to
access each element of the array.
Inside the loop, we are calculating the sum of each
element. Notice the line,
Multidimensional Arrays
Arrays we have mentioned till now are called one-
dimensional arrays. However, we can declare
multidimensional arrays in Java.
A multidimensional array is an array of arrays. That is,
each element of a multidimensional array is an array itself.
For example,
double[][] matrix = {{1.2, 4.3, 4.0},
{4.1, -1.1}
};
Initialization of 2-
dimensional Array
Example: 2-dimensional Array
class MultidimensionalArray {
public static void main(String[] args) {
// create a 2d array
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
Output:
Length of row 1: 3
Length of row 2: 4
Length of row 3: 1
class MultidimensionalArray {
public static void main(String[] args) {
int[][] a = {
{1, -2, 3},
{-4, -5, 6, 9},
{7},
};
Output:
1
-2
3
-4
-5
6
9
7
We can also use the for...each loopto access elements of
the multidimensional array. For example,
class MultidimensionalArray {
public static void main(String[] args) {
// create a 2d array
int[][] a = {
{1, -2, 3},
{-4, -5, 6, 9},
{7},
};
Output:
1
-2
3
-4
-5
6
9
7
// test is a 3d array
int[][][] test = {
{
{1, -2, 3},
{2, 3, 4}
},
{
{-4, -5, 6, 9},
{1},
{2, 3}
}
};
class ThreeArray {
public static void main(String[] args) {
// create a 3d array
int[][][] test = {
{
{1, -2, 3},
{2, 3, 4}
},
{
{-4, -5, 6, 9},
{1},
{2, 3}
}
};
// for..each loop to iterate through
elements of 3d array
for (int[][] array2D: test) {
for (int[] array1D: array2D) {
for(int item: array1D) {
System.out.println(item);
}
}
}
}
}
Output:
1
-2
3
2
3
4
-4
-5
6
9
1
2
3
Java String
class Main {
public static void main(String[] args) {
// create strings
String first = "Java";
String second = "Python";
String third = "JavaScript";
// print strings
System.out.println(first); // print Java
System.out.println(second); // print
Python
System.out.println(third); // print
JavaScript
}
}
// create a string
String greet = "Hello! World";
System.out.println("String: " + greet);
// create second
String second = "Programming";
System.out.println("Second String: " +
second);
Output
First String: Java
Second String: Programming
Joined String: Java Programming
// create 3 strings
String first = "java programming";
String second = "java programming";
String third = "python programming";
Output
Strings first and second are equal: true
Strings first and third are equal: false
returns the
substring() substring of
the string
replaces the
specified old
replace() character with
the specified
new character
returns the
character
charAt() present in the
specified
location
converts the
getBytes() string to an
array of bytes
returns the
position of the
indexOf() specified
character in
the string
compares two
strings in the
compareTo()
dictionary
order
removes any
leading and
trim()
trailing
whitespaces
returns a
format() formatted
string
breaks the
string into an
split()
array of
strings
converts the
toLowerCase() string to
lowercase
converts the
toUpperCase() string to
uppercase
returns the
string
representation
valueOf()
of the
specified
argument
converts the
toCharArray() string to a
char array
// create a string
String example = "Hello! ";
Here, we have created a string variable named example.
The variable holds the string "Hello! ".
Now suppose we want to change the string.
class Main {
public static void main(String[] args) {
// abstract method
abstract void method1();
// regular method
void method2() {
System.out.println("This is regular
method");
}
}
// error
// class should be abstract
class Language {
// abstract method
abstract void method1();
}
Output
This is Java programming
obj.display();
Here, obj is the object of the child class Main. We are
calling the method of the abstract class using the
object obj.
class Main {
public static void main(String[] args) {
d1.makeSound();
d1.eat();
}
}
Output
Bark bark
I can eat.
Java Interface
Here,
• Language is an interface.
• It includes abstract
methods: getType() and getVersion().
Implementing an Interface
Like abstract classes, we cannot create objects of
interfaces.
To use an interface, other classes must implement it. We
use the implements keyword to implement an interface.
Example 1: Java Interface
interface Polygon {
void getArea(int length, int breadth);
}
class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
r1.getArea(5, 6);
}
}
Output
The area of the rectangle is 30
// create an interface
interface Language {
void getName(String name);
}
// class implements interface
class ProgrammingLanguage implements Language {
class Main {
public static void main(String[] args) {
ProgrammingLanguage language = new
ProgrammingLanguage();
language.getName("Java");
}
}
Output
Programming Language: Java
interface A {
// members of A
}
interface B {
// members of B
}
class C implements A, B {
// abstract members of A
// abstract members of B
}
Extending an Interface
Similar to classes, interfaces can extend other interfaces.
The extends keyword is used for extending interfaces.
For example,
interface Line {
// members of Line interface
}
// extending interface
interface Polygon extends Line {
// members of Polygon interface
// members of Line interface
}
Here, the Polygon interface extends the Line interface.
Now, if any class implements Polygon, it should provide
implementations for all the abstract methods of
both Line and Polygon.
interface A {
...
}
interface B {
...
}
interface C extends A, B {
...
}
Advantages of Interface in Java
Now that we know what interfaces are, let's learn about
why interfaces are used in Java.
• Similar to abstract classes, interfaces help us to
achieve abstraction in Java.
• interface Polygon {
• …
• }
•
// by default public
void getName();
}
interface Polygon {
void getArea();
// default method
default void getSides() {
System.out.println("I can get sides of a
polygon.");
}
}
class Main {
public static void main(String[] args) {
Output
The area of the rectangle is 30
I have 4 sides.
The area of the square is 25
I can get sides of a polygon.
// create an interface
interface Polygon {
staticMethod(){..}
}
interface Polygon {
void getArea();
System.out.println("Perimeter: " +
perimeter);
}
}
class Main {
public static void main(String[] args) {
Triangle t1 = new Triangle(2, 3, 4);
Output
Area: 2.9047375096555625
Perimeter: 9