Unit - 1
Unit - 1
class Animal {
public void method1() {...}
Java Class
A class is a blueprint for the object. Before we create an object, we first
need to define the class.
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
}
class Bicycle {
// state or field
private int gear = 5;
// behavior or method
public void braking() {
System.out.println("Working of Braking");
}
}
Note: We have used keywords private and public . These are known
as access modifiers. To learn more, visit Java access modifiers.
Java Objects
An object is called an instance of a class. For example,
suppose Bicycle is a class
then MountainBicycle , SportsBicycle , TouringBicycle , etc can be
considered as objects of the class.
Creating an Object in Java
Note: Fields and methods of a class are also called members of the
class.
class Bicycle {
// field of class
int gear = 5;
// method of class
void braking() {
...
}
}
// create object
Bicycle sportsBicycle = new Bicycle();
We have mentioned the word method quite a few times. You will learn
about Java methods in detail in the next chapter.
Now that we understand what is class and object. Let's see a fully
working example.
Example: Java Class and Objects
class Lamp {
class Main {
public static void main(String[] args) {
Output:
Inside the Main class, we have created two objects: led and halogen of
the Lamp class. We then used the objects to call the methods of the
class.
led.turnOn() - It sets the isOn variable to true and prints the output.
halogen.turnOff() - It sets the isOn variable to false and prints the
output.
The variable isOn defined inside the class is also called an instance
variable. It is because when we create an object of the class, it is called
an instance of the class. And, each instance will have its own copy of
the variable.
That is, led and halogen objects will have their own copy of
the isOn variable.
Example: Create objects inside the same class
Note that in the previous example, we have created objects inside
another class and accessed the members from that class.
class Lamp {
Output
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
Here, Test() is a constructor. It has the same name as that of the class
and doesn't have a return type.
Recommended Reading: Why do constructors not return values
Example 1: Java Constructor
class Main {
private String name;
// constructor
Main() {
System.out.println("Constructor Called:");
name = "Programiz";
}
Output:
Constructor Called:
The name is Programiz
Inside the constructor, we are initializing the value of the name variable.
Notice the statement of creating an object of the Main class.
Here, when the object is created, the Main() constructor is called. And,
the value of the name variable is initialized.
Hence, the program prints the value of the name variables as Programiz .
Types of Constructor
1. No-Arg Constructor
2. Parameterized Constructor
3. Default Constructor
private Constructor() {
// body of the constructor
}
Example 2: Java private no-arg constructor
class Main {
int i;
Output:
Constructor is called
Value of i: 5
// public constructor
public Company() {
name = "Programiz";
}
}
class Main {
public static void main(String[] args) {
Output:
String languages;
Here, we are passing the single value to the constructor. Based on the
argument passed, the language variable is initialized inside the
constructor.
int a;
boolean b;
public static void main(String[] args) {
System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}
Run Code
Output:
Default Value:
a = 0
b = false
boolean false
byte 0
short 0
int 0
long 0L
char \u0000
float 0.0f
double 0.0d
In the above program, the variables a and b are initialized with default
value 0 and false respectively.
The above program is equivalent to:
class Main {
int a;
boolean b;
Main() {
a = 0;
b = false;
}
System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}
Run Code
Constructor types:
No-Arg Constructor - a constructor that does not accept any
arguments
Parameterized constructor - a constructor that accepts arguments
Default Constructor - a constructor that is automatically created by the
Java compiler if it is not explicitly defined.
A constructor cannot be abstract or static or final .
A constructor can be overloaded but can not be overridden.
String language;
obj1.getName();
obj2.getName();
}
}
Run Code
Output:
Now, if the same method is defined in both the superclass and the
subclass, then the method of the subclass class overrides the method
of the superclass. This is known as method overriding.
class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}
Run Code
Output:
I am a dog.
class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}
Run Code
Output:
I am an animal.
I am a dog.
And we can invoke static methods directly using the class name. For
example,
class Test {
// static method inside the Test class
public static void method() {...}
}
class Main {
// invoking the static method
Test.method();
}
Here, we can see that the static method can be accessed directly from
other classes using the class name.
// 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
Inside the Main class, we can see that we are calling the non-static
method using the object of the class ( st.multiply(2, 2) ). However, we
are calling the static method by using the class name
( StaticTest.add(2, 3) ).
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.
class Test {
// static variable
static int age;
}
class Main {
// access the static variable
Test.age = 20;
}
Here, we can see that we are accessing the static variable from the
other class using the class name.
// static variable
static int max = 10;
// non-static variable
int min = 5;
}
Output:
min + 1 = 6
max + 1 = 11
Inside the Main class, we can see that we are calling the non-static
variable using the object of the class ( obj.min + 1 ). However, we are
calling the static variable by using the class name ( Test.max + 1 ).
Note: Static variables are rarely used in Java. Instead, the static
constants are used. These static constants are defined by static
final keyword and represented in uppercase. This is why some people
prefer to use uppercase for static variables as well.
// 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
Here, we are able to access the static variable and method directly
without using the class name. It is because static variables and
methods are by default public. And, since we are accessing from the
same class, we don't have to specify the class name.
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
}
The static block is executed only once when the class is loaded in
memory. The class is loaded if either the object of the class is
requested in code or the static members are requested in code.
A class can have multiple static blocks and each static block is
executed in the same sequence in which they have been written in a
program.
// 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:
The first static block is executed. Hence, the string First Static
The second static block is executed. Hence, the string Second Static
And finally, the print statements inside the method display() are
executed.
Nested Static Class
In Java, we can declare a class inside another class. Such classes are
known as nested classes. Nested classes are of 2 types:
For example,
class OuterClass {
// static nested class
static class NestedClass {...}
Stringoperation1.java
Output:
SACHIN
sachin
Sachin
Stringoperation2.java
Output:
Sachin
Sachin
Stringoperation3.java
Output:
true
true
Java String charAt() Method
The String class charAt() method returns a character at specified
index.
Stringoperation4.java
Output:
S
h
Stringoperation5.java
Output:
6
Stringoperation6.java
Output:
Sachin
Stringoperation7.java
1. public class Stringoperation7
2. {
3. public static void main(String ar[])
4. {
5. int a=10;
6. String s=String.valueOf(a);
7. System.out.println(s+10);
8. }
9. }
Output:
1010
Stringoperation8.java
Output:
Kava is a programming language. Kava is a platform. Kava is an Island.
Java Command-Line Arguments
javac Main.java
java Main
The String array stores all the arguments passed through the
command line.
}
}
Run Code
1. // a final variable
2. final double PRICE;
3. final int COUNT = 5;
4. // a final static variable PI
5. static final double PRICE;
6. static final double PI = 3.141;
Note: In the case of the reference final variable, the internal state of the object pointed
by that reference variable can be changed but it is not re-assigning of a reference
variable. The mechanism is known as non-transitivity.
1. class Demo
2. {
3. final void display()
4. {
5. System.out.println("Inside final method.");
6. }
7. }