0% found this document useful (0 votes)
2 views33 pages

JavaM1 P3

The document provides an overview of Java programming concepts, focusing on constructors, including default, parameterized, and copy constructors, as well as constructor overloading and chaining. It also explains access modifiers, garbage collection, the use of the 'this' and 'super' keywords, static variables and methods, nested classes, abstract classes, and the final keyword. Each concept is illustrated with code examples to demonstrate their usage in Java.

Uploaded by

lenovo ji
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)
2 views33 pages

JavaM1 P3

The document provides an overview of Java programming concepts, focusing on constructors, including default, parameterized, and copy constructors, as well as constructor overloading and chaining. It also explains access modifiers, garbage collection, the use of the 'this' and 'super' keywords, static variables and methods, nested classes, abstract classes, and the final keyword. Each concept is illustrated with code examples to demonstrate their usage in Java.

Uploaded by

lenovo ji
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
You are on page 1/ 33

Java Programming

Module-1 Part3

1
Constructor
• A constructor automatically initializes an object immediately upon creation.

• Its name is same as of class name.

• No return type not even void. Implicit return type of a class constructor is class itself.

• If we do not define a constructor for a class, Java creates a default constructor for the class.
This constructor initializes all instance variables to zero. If we define a constructor then
default constructor is no longer used.
Default
Parameterized
Copy
Do nothing: can not contain definition. Used for creating objects without
initialization.
Constructor
• we can have private, protected, public or default constructor in Java.

• A Java constructor cannot be abstract, static, final, and synchronized.

• Constructor is automatically called immediately after the object is created before the
new operator completes.

• Java provides a Constructor class which can be used to get the internal information of
a constructor in the class. It is found in the java.lang.reflect package.
Constructor Overloading
class Box double volume() vol = mybox2.volume();
{ { System.out.println(" Volume of
double width, height, depth; return width * height * depth; mybox2 is " + vol);
}
Box(double w, double h, double d) vol = mycube.volume();
}
{ System.out.println(" Volume of
width = w; height = h; depth = d; public class Test mycube is " + vol);
{ }
}
public static void main(String args[]) }
Box() {
{ Box mybox1 = new Box(10, 20, 15);
width = height = depth = 0; Box mybox2 = new Box(); O/P:
Box mycube = new Box(7); Volume of mybox1 is 3000.0
}
Box(double len) double vol; Volume of mybox2 is 0.0
{
width = height = depth = len; vol = mybox1.volume(); Volume of mycube is 343.0
System.out.println(" Volume of
}
mybox1 is " + vol);
Copy Constructor
class Student{
int id;
String name;
Student(int i,String n){
id = i;
name = n;
}
Student(Student s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student s1 = new Student(111,“RAM");
Student s2 = new Student(s1);
s1.display();
s2.display();
}
5
We can copy the values of one object into another by assigning the objects values to
another object. In this case, there is no need to create the constructor.
class Student{
int id;
String name;
Student(int i,String n){
id = i;
name = n;
}
Student(){}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student s1 = new Student(111,"Karan");
Student s2 = new Student();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
6
} }
Output?
class Example
{
private int var;
public Example(int num)
{
var=num;
}
public int getValue() Compiler Error
{
return var;
}
public static void main(String args[])
{
Example myobj = new Example();
System.out.println("value of var is: "+myobj.getValue());
}
}
7
Constructor Chaining

• Calling a constructor from the another constructor of same class is known as


Constructor chaining.

• It allows us to initialize only from a single location while providing multiple


constructors to the user.

• Constructor chaining can be achieved in any order.

• this() should always be the first statement in constructor.

• There should be at-least be one constructor without the this() keyword.

• In subclass we can call constructor of parent class using super()(as a first statement),
but not vice versa.
8
class Main public void display()
{ {
int age; System.out.println("Name="+name+"\nage="+age);
String name; }
Main() public static void main(String args[])
{ {
this("Constructor Example"); Main obj = new Main();
} obj.display();
}
Main(String s) }
{
this(s,6);
}
Main(String s1,int a)
{
this.name=s1;
age=a;
}
9
Access Modifier
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.
Access within class within outside outside
Modifier package package by package
subclass only

Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Garbage Collection
• Objects are dynamically allocated in Java using new operator. In C++, delete operator is
used when object is created dynamically but in Java, different approach(garbage
collection) is used to handle this.

• When no reference to an object exist, that object is assumed to be no longer needed and
the memory occupied by that object can be reclaimed. There is no explicit need to
destroy the objects like C++.

• Garbage collector runs periodically , checking for objects that are no longer referred. It is
low priority thread.

• Specific actions can be performed by an object before an object is destroyed(when it is


just about to be reclaimed by the garbage collector).

• These actions are performed using. finalize() method.


• finalize( ) method is called at run time when the object is about to recycle .
protected void finalize()
{
}
• There is no guarantee about the time when finalize is called. It may be called any
time after the object is not being referred anywhere (can be garbage collected).

• In C++, destructor is used, which is called when an object goes out of scope. Java
does not support destructor. The finalizer() method only approximates the need
of destructor.

• It can be public or protected. Best to make it as protected.


public class Main
{
• We can call finalize method Explicitly then it will be
public static void main(String[] args) executed just like normal method call but object won’t be
deleted/destroyed
{
Main s = new Main(); class Hello {
s.show(); public static void main(String[] args)
{
s=null; Hello s = new Hello();
System.gc(); //request to call garbage collector s.show();
s. finalize();
} }
void show() void show()
{
{ System.out.println(“Hello”);
System.out.println("Hello"); }
protected void finalize()
} {
protected void finalize() System.out.println("finalize method”);
}
{ System.out.println("finalize method"); }
} O/P: Hello
} finalize method
Difference between Destructor and finalize()

• Every object is destroyed when it goes out of scope.

• Destructor is called automatically just before destruction of the object.

• In Java, objects are not explicitly destroyed when they go out of scope. Object is marked
as unused when there are no longer any references pointing to it.

• finalize() method will not be called until the garbage collector runs. Even if you
execute a call to gc( ) (the garbage collector), there is no guarantee that finalize( ) will
immediately be executed.
this keyword
• this is a reserved keyword in java.
• this is used to refer current-class’s instance as well as static members.
class Main
public static void main(String[] args) If b is static then
{
{ O/P: 40
int a = 10; 30
Main a=new Main(40,60);
int b = 20; //can be static also 30
Main b=new Main(30,30); 30
Main(int a, int b)
a.show();
{
b.show();
this.a=a;
}
this.b=b;
}
}
void show() O/P: 40
{ 60
System.out.println(a); 30
30
System.out.println(b);
}
Super keyword
• super is a reserved keyword in java.
• super can be used to refer immediate parent class instance variable.
• super can be used to invoke immediate parent class method.
• super( ) can be used to invoke immediate parent class constructor.
class A class Test
{ {
int a=10; public static void main(String args[])
} {
class B extends A B obj=new B();
{ obj.print();
int a=20; }
void print () }
{
System.out.println(a); O/P: 20
System.out.println(super.a); 10
}
}
Super Keyword
The super keyword can also be used to invoke parent class method. It should be
used if subclass contains the same method as parent class(if method is
class A
overridden) super.show();
{
}
void show() }
{ class Main
System.out.println("A Class"); {
public static void main(String args[])
} {
} B obj=new B();
class B extends A{ obj.show();
obj.ashow();
void show()
{ }}
System.out.println("B Class");
O/P: B Class
} A class
void ashow()
Super Keyword

• Used to invoke parent class constructor.

• Argument of super must be same as the argument of base class


constructor.

• It must be called inside the constructor of subclass as a first statement. .


class A
{ class Main
int a,b,c; {
A(int x, int y) public static void main(String args[])
{ a=x; b=y; c=a+b; {
System.out.println(c); B obj=new B(5,10,15);
} }
} }
class B extends A
{ O/P: 15
int d,e,f,g; 30
B(int p, int q, int r)
{
super(p,q);
d=p; e=q; f=r;
g=d+e+f; System.out.println(g);
}
}
Static variable
▪ Static data members has the Public class Main
common properties to all objects. {
O/P:
public static void main(String
a=10
class Test() args[]) b=10
{ { a=10
int a; Test obj1=new Test(); b=10
static int b; Test obj2=new Test(); a=11
void setvalue() obj1.setvalue(); b=11
{ obj1.display(); a=11
a=10, b=10;} obj2.setvalue(); b=12
obj2.display(); a=12
void display() b=13
obj1.display();
{ obj2.display();
System.out.println(“a=“+a); obj2.display();
System.out.println(“b=“+b); }
a++;b++; }

}}
static method

• It can access only static data members and will execute without any object.
• It will be invoked before any creating any object and can also be invoked by the class name.

class A class Main


{ {
public static void main(String args[])
static int a=10; {
static void fun() A.fun();
{ }
System.out.println(a); }

}
static
statement
• Static statements are executed before creating any object.
• Used to initialize static data members like constructers helps to initialize instance members.

class A
{ class Main
static int a=10; {
static public static void main(String args[])
{ {
System.out.println(a); A obj=new A();
} obj.fun();
void fun() }
{ }
System.out.println("Non static function"); O/P: 10
} Non static function

}
Static class
• Java allows a class to be defined within another class. These are called Nested Classes.
• The class in which the nested class is defined is known as the Outer Class. Unlike top-
level classes, Inner classes can be Static. Non-static nested classes are also known
as Inner classes.

• We can declare a class static by using the static keyword. A class can be declared static
only if it is a nested class. It does not require any reference of the outer class. The
property of the static class is that it does not allows us to access the non-static members
of the outer class.
Inner class
• The classes that are non-static and nested are called inner classes.
• We cannot create an instance of the inner class without creating an instance of the outer class.
Without using the reference to the outer class instance, an instance of the inner class can
access the members of its outer class. It makes the program simple and concise.

Outer Class
• The class in which nested class is defined is called outer class.

Nested Class
• Java allows us to define a class within a class that is known as a nested class.
• It may be static or non-static. The major difference between static and non-static class is that:
• An instance of the static nested class can be created without creating an instance of its outer
class.
• The static and non-static members of an outer class can be accessed by an inner class.
.
• All static classes are nested classes but vice-versa is not true.

• Static class can access only static members of the outer class.

• Non-static variable and instance methods cannot be accessed within the static class.
If you try to access a non-static reference from a static field, it throws an
error: Cannot make a static reference to the non-static field.

• We can create static blocks, variables, and methods inside a static class.

• A class may have multiple static classes.

• We cannot access the static class if it is inside the static block.

• There may be any number of static classes within a static class.


public class Main
public void display()
{ {
private static String s= "Example of static class"; System.out.println(s);
System.out.println(a);
int a=10;
//Static and nested class }
static class nested }

{ public static void main(String args[])


public void show() {
Main.nested obj = new Main.nested ();
{
//prints the string defined in base class //invoking the method of the nested class
System.out.println(s); obj.show();
Main m=new Main();
//System.out.println(a); error
Main.InnerClass obj1 = m.new InnerClass();
}} obj1.display();
public class InnerClass
}
{
// Both static and non-static members of Outer class
are accessible in this Inner class
Abstract Class and Abstract Method
• A class whose object is not created directly is known as abstract class.

• Used as superclass.

• Abstract class can not be directly initialized using new operator.


abstract class name
{
}
• Abstract method is used in interface.

• Helps in generalization of methods and to define subclass features efficiently.

• Class having abstract method can not have its definition. Definition of abstract method is given in subclass.
abstract type name(parameter-list)
{
}
Abstract Class and Abstract Method
abstract class Base public class Main
{ {
public static void main(String args[ ])
abstract void display();
{
} Derived obj1 = new Derived();
class Derived extends Base obj1.display();
{ }
}
void display()
{
System. out. println(“abstract method called");
}
}
Final Keyword
• final keyword is used to define final variable, method or class.

• final variable is a variable whose value can not be changed during the execution of
program.

• A final variable is called blank final variable, if it is not initialized while declaration.

• A blank final variable can be initialized inside instance-initializer block or inside


constructor. If there is more than one constructor, then it must be initialized in all of
them, otherwise compile time error will be thrown.

• A blank final static variable can be initialized inside static block.


class Main
class A
{
{ final int a; int b;
public static void main(String args[])
A( )
{
{ a=10;
A obj=new A();
System.out.println(a);
A obj1=new A(9);
}
}
A(int x)
}
{
b=x;
O/P: error a has not been initialized
System.out.println(b);
}
}

31
Final Keyword

• final method is a method which can not be redefine is subclass. It is used to restrict
the method overriding.

• final method is inherited but cannot override it.

• final class is a class which can not be inherited.

• const variables in C++ must be assigned a value when declared. For final variables in
Java, it is not necessary. A final variable can be assigned value later, but only once.
class A final class A{
class A
{ void show( )//final method
{ final void show( )//final method {
final int a=90;//final variable { System. out. println ("show method A");
void show() System. out. println ("show method A"); } }//final class
{ }
} class B extends A
a=400;
class B extends A{ {
} void run()
void show( ){
public static void main(String args[]) System.out.println("show method B"); {
System. out. println(“final class example”)
{ } }
A obj=new A(); public static void main(String args[])
obj. run(); { public static void main(String args[])
B obj= new B(); {
} B obj= new B();
obj.show();
} obj.run();
}}
}
Compile time error } Compile time error
Compile time error

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy