0% found this document useful (0 votes)
10 views

Java Notes

Uploaded by

pratiktayade822
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Java Notes

Uploaded by

pratiktayade822
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Java Constructors

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 constructor, memory for the object is allocated in the
memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one constructor is called.

It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.

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:

Example

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

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

System.out.println(myObj.x); // Print the value of x

Types of Java constructors


There are two types of constructors in Java:

1. Default constructor (no-arg constructor)

2. Parameterized constructor
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:

<class_name>(){}

Example of default constructor

In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creatio

//Java Program to create and call a default constructor

class Bike1{

//creating a default constructor

Bike1(){System.out.println("Bike is created");}

//main method

public static void main(String args[]){

//calling a default constructor

Bike1 b=new Bike1();

Example of default constructor that displays the default values


//Let us see another example of default constructor

//which displays the default values

class Student3{

int id;

String name;

//method to display the value of id and name

void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects

Student3 s1=new Student3();

Student3 s2=new Student3();

//displaying values of the object

s1.display();

s2.display();

Java Parameterized Constructor


A constructor which has a specific number of parameters is called a parameterized constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct objects. However,
you can provide the same values also.

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two parameters. We
can have any number of parameters in the constructor.

//Java Program to demonstrate the use of the parameterized constructor.

class Student4{

int id;

String name;

//creating a parameterized constructor

Student4(int i,String n){

id = i;

name = n;

//method to display the values

void display(){System.out.println(id+" "+name);}

public static void main(String args[]){

//creating objects and passing values

Student4 s1 = new Student4(111,"Karan");

Student4 s2 = new Student4(222,"Aryan");

//calling method to display the values of object

s1.display();
s2.display();

Constructor Overloading in Java


In Java, a constructor is just like a method but without return type. It can also be overloaded
like Java methods.

Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a
different task. They are differentiated by the compiler by the number of parameters in the
list and their types.

Example of Constructor Overloading

//Java program to overload constructors

class Student5{

int id;

String name;

int age;

//creating two arg constructor

Student5(int i,String n){

id = i;

name = n;

//creating three arg constructor

Student5(int i,String n,int a){

id = i;

name = n;

age=a;

void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){

Student5 s1 = new Student5(111,"Karan");

Student5 s2 = new Student5(222,"Aryan",25);

s1.display();
s2.display();

Access Modifiers in Java


There are two types of modifiers in Java: access modifiers and non-access modifiers. The access
modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can
change the access level of fields, constructors, methods, and class by applying the access modifier on
it.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.

2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.

3. Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.

4. Public: The access level of a public modifier is everywhere. It can be accessed from within
the class, outside the class, within the package and outside the package.

There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.

1) Private
The private access modifier is accessible only within the class.

Simple example of private access modifier

In this example, we have created two classes A and Simple. A class contains private data member and
private method. We are accessing these private members from outside the class, so there is a
compile-time error.

class A{

private int data=40;

private void msg(){System.out.println("Hello java");}


}

public class Simple{

public static void main(String args[]){

A obj=new A();

System.out.println(obj.data);//Compile Time Error

obj.msg();//Compile Time Error

Role of Private Constructor

If you make any class constructor private, you cannot create the instance of that class from outside
the class. For example:

class A{

private A(){}//private constructor

void msg(){System.out.println("Hello java");}

public class Simple{

public static void main(String args[]){

A obj=new A();//Compile Time Error

Note: A class cannot be private or protected except nested class.

2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is accessible
only within package. It cannot be accessed from outside the package. It provides more accessibility
than private. But, it is more restrictive than protected, and public.

Example of default access modifier

In this example, we have created two packages pack and mypack. We are accessing the A class from
outside its package, since A class is not public, so it cannot be accessed from outside the package.

//save by A.java

package pack;

class A{

void msg(){System.out.println("Hello");}
}

//save by B.java

package mypack;

import pack.*;

class B{

public static void main(String args[]){

A obj = new A();//Compile Time Error

obj.msg();//Compile Time Error

In the above example, the scope of class A and its method msg() is default so it cannot be accessed
from outside the package.

3) Protected
The protected access modifier is accessible within package and outside the package but through
inheritance only.

The protected access modifier can be applied on the data member, method and constructor. It can't
be applied on the class.

It provides more accessibility than the default modifer.

In this example, we have created the two packages pack and mypack. The A class of pack package is
public, so can be accessed from outside the package. But msg method of this package is declared as
protected, so it can be accessed from outside the class only through inheritance.

//save by A.java

package pack;

public class A{

protected void msg(){System.out.println("Hello");}

//save by B.java

package mypack;

import pack.*;

class B extends A{

public static void main(String args[]){

B obj = new B();

obj.msg();
}

Output:Hello

4) Public

The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.

Example of public access modifier

//save by A.java

package pack;

public class A{

public void msg(){System.out.println("Hello");}

//save by B.java

package mypack;

import pack.*;

class B{

public static void main(String args[]){

A obj = new A();

obj.msg();

Output:Hello

Java Access Modifiers with Method Overriding

If you are overriding any method, overridden method (i.e. declared in subclass) must not be more
restrictive.

class A{

protected void msg(){System.out.println("Hello java");}


}

public class Simple extends A{

void msg(){System.out.println("Hello java");}//C.T.Error

public static void main(String args[]){

Simple obj=new Simple();

obj.msg();

Java static keyword


The static keyword in Java is used for memory management mainly. We can apply static keyword
with variables, methods, blocks and nested classes. The static keyword belongs to the class than an
instance of the class.

1. Variable (also known as a class variable)

2. Method (also known as a class method)

3. Block

4. Nested class

o The static variable can be used to refer to the common property of all objects (which is not
unique for each object), for example, the company name of employees, college name of
students, etc.

o The static variable gets memory only once in the class area at the time of class loading.

Advantages of static variable

It makes your program memory efficient (i.e., it saves memory).

Understanding the problem without static variable


class Student{

int rollno;

String name;

String college="ITS";

Suppose there are 500 students in my college, now all instance data members will get memory each
time when the object is created. All students have its unique rollno and name, so instance data
member is good in such case. Here, "college" refers to the common property of all objects. If we
make it static, this field will get the memory only once.

Example of static variable

//Java Program to demonstrate the use of static variable

class Student{

int rollno;//instance variable

String name;

static String college ="ITS";//static variable

//constructor

Student(int r, String n){

rollno = r;

name = n;

//method to display the values

void display (){System.out.println(rollno+" "+name+" "+college);}

//Test class to show the values of objects

public class TestStaticVariable1{

public static void main(String args[]){

Student s1 = new Student(111,"Karan");

Student s2 = new Student(222,"Aryan");

//we can change the college of all objects by the single line of code

//Student.college="BBDIT";

s1.display();

s2.display();

Output:
111 Karan ITS

222 Aryan ITS

Program of the counter without static variable

In this example, we have created an instance variable named count which is incremented in the
constructor. Since instance variable gets the memory at the time of object creation, each object will
have the copy of the instance variable. If it is incremented, it won't reflect other objects. So each
object will have the value 1 in the count variable.

//Java Program to demonstrate the use of an instance variable

//which get memory each time when we create an object of the class.

class Counter{

int count=0;//will get memory each time when the instance is created

Counter(){

count++;//incrementing value

System.out.println(count);

public static void main(String args[]){

//Creating objects

Counter c1=new Counter();

Counter c2=new Counter();

Counter c3=new Counter();

}
Program of counter by static variable

As we have mentioned above, static variable will get the memory only once, if any object changes
the value of the static variable, it will retain its value.

//Java Program to illustrate the use of static variable which

//is shared with all objects.

class Counter2{

static int count=0;//will get memory only once and retain its value

Counter2(){

count++;//incrementing the value of static variable

System.out.println(count);

public static void main(String args[]){

//creating objects

Counter2 c1=new Counter2();

Counter2 c2=new Counter2();

Counter2 c3=new Counter2();

2) Java static method

If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than the object of a class.

o A static method can be invoked without the need for creating an instance of a class.

o A static method can access static data member and can change the value of it.

Example of static method

//Java Program to demonstrate the use of a static method.

class Student{

int rollno;

String name;

static String college = "ITS";

//static method to change the value of static variable

static void change(){

college = "BBDIT";
}

//constructor to initialize the variable

Student(int r, String n){

rollno = r;

name = n;

//method to display values

void display(){System.out.println(rollno+" "+name+" "+college);}

//Test class to create and display the values of object

public class TestStaticMethod{

public static void main(String args[]){

Student.change();//calling change method

//creating objects

Student s1 = new Student(111,"Karan");

Student s2 = new Student(222,"Aryan");

Student s3 = new Student(333,"Sonoo");

//calling display method

s1.display();

s2.display();

s3.display();

Output:111 Karan BBDIT

222 Aryan BBDIT

333 Sonoo BBDIT

Another example of a static method that performs a normal calculation

//Java Program to get the cube of a given number using the static method

class Calculate{

static int cube(int x){

return x*x*x;
}

public static void main(String args[]){

int result=Calculate.cube(5);

System.out.println(result);

Restrictions for the static method

There are two main restrictions for the static method. They are:

The static method can not use non static data member or call non-static method directly.

this and super cannot be used in static context.

class A{

int a=40;//non static

public static void main(String args[]){

System.out.println(a);

3) Java static block

o Is used to initialize the static data member.

o It is executed before the main method at the time of classloading.

Example of static block

class A2{

static{System.out.println("static block is invoked");}

public static void main(String args[]){

System.out.println("Hello main");

You might also like