0% found this document useful (0 votes)
29 views26 pages

Unit 2 (Java Btech)

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)
29 views26 pages

Unit 2 (Java Btech)

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/ 26

UNIT-2

Classes and objects:


• Class is a blue print or prototype from which objects are created
• Object is anything in the realworld entity.

Class declaration and 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 modifiers on it.

1.private access modifier:


• The access level of private modifier is only with in the class.it cannot be accessed from
out side the class.
• Here, A class contains private data members and private method
• We are accessing these private members from outside the class, so there is a compile
time error.

Ex:
class A
{
Private int x=10;
Private void msg()
{
System.out.println(“hello”);
}
}
Public class B
{
Public static void main(String args[])
{
A obj=new A();
System.out.println(obj.x);
Obj.msg();

1
}
}
Output:compile time error.
2.public:
• The access level of public modifier is everywhere.
• It can be accessed from with in the class outside the class,with in the package and
outside the package.

Ex:

package x;
public class A
{
Public void msg()
{
System.out.println(“hello”);
}
//save by B
Import x.*;
Class B
{
public static void main(String args[])
{
A obj=new A();
Obj.msg();
}
}
Output: hello.
3.default:
• If you don’t use any modifier, it is located as default by default.
• The default modifier is accessible only within the package.it cannot be accessed from
outside the package.
• It provides more accessibility than private, but it is more restrictive than protected and
public.

2
Ex:
//saved by A.java
Package x;
class A
{
Void msg()
{
System.out.println(“hello”);
}
}
//saved by B.java
Import x.*;
Class B
{
Public static void main(String args[])
{
A obj=new A();
obj.msg();
}
}
Output: compile time error.
• Here scope of a class A and its method msg() is default.so it cannot be accessed from
out of the package.

4.protected:
• The 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 cannot be applied on the class.
• It provides more accessibility than the default modifier.

Ex://save by A.java
Package x;
Public class A
3
{
Protected void msg()
{
System.out.println(“hello”);
}
}
//save by B.java
Import x.*;
Class B extends A
{
Public static void main(String args[])
{
B obj=new B();
Obj.msg();
}
}
Output:
Hello

non-access modifiers:
• There are many non-access modifiers, such as static,abstract,synchronized etc.
• There are 7 types of non access modifiers available in java.
1.static:

• static keyword in java is used for memory management.it can be applicable for
methods,variables,blocks etc.
2.final:

• final keyword indicates that specific class cannot be extended or a method cannot be
over ridden.
3.abstract:

• abstraction is a process of hiding the internal details and showing the functionality to
the user.
4.synchronized:

4
• this keyword prevents block of code from executing multiple threads at once.it is very
important for some critical operations.
5.volatile:

• the volatile keyword is only applicable to a variable.by using this keyword every
reading and writing operations will be done directly on the main memory. i.e, memory
management.
6.transient:
• this needs a prior knowledge of serialization. serialization is used to convert an object
into a stream of bytes.
• Deserialization performs exactly an opposite operation.it is used with data members of
a class in order to avoid their serialization.
• When jvm reads transient keyword.it ignores the original value of the object instead it
stores the default value of the object.
Ex: if a program accepts a user’s login details and password. but we don’t want to store the
original password in the file. here we can use transient keyword.
Syntax: private transient<member value>;
7.native keyword:

• It makes a method. that it will be implemented in other languages.


• The method is declared without a body and cannot be abstract.
CLASS MEMBERS:
• The members of the class i.e, class members are defined inside the body of the class.
• They consists of various methods, fields, nested classes and interfaces.
• In java programming language class member is a field or method that is part of a class
• They contain both the members, that are defined in the class and that are inherited from
a super class.
• In a simple way everything which is declared inside the class are members of class
• There are two types fields and methods
• There are three types of variables available for a class they are as follows:

1.local variable:

• A variable which is declared inside the body of the method is known as local variable.

5
• You can use this variable only with in the method and other methods in the class are
not even aware that the variable exists.
• Local variable cannot be defined with static.
2.instance variable:

• A variable is declared inside the class but outside the body of the method is known as
instance variable.
• It is not declared as static.
3.static variable:
• A variable which is declared with a static keyword is known as ststic variable
• It cannot be local

Ex:
Class A
{
Int data=10;//instance variable
Static int m=100;//static variable
Void method()
{
Int n=1000;
}
}
Method:
• Method is a block of code or collection of statements or set of code grouped together
to perform specific task
• It is used to achieve reusability of code
• The method is executed only when we call or invoke it.
• The most important method in java is the main() method.
Method declaration:

• Method declaration provides information about return type,access specifier, arguments


and method name
• It has six components as shown in the below figure:

6
Naming a method:

• While defining a method, remember that the method name must be a verb and start with
a lowercase letter.
• If the method name has more than two words, the first name must be a verb followed
by adjective or noun.
• In the multi-word method name, the first letter of each word must be
in uppercase except the first word. For example:

Single-word method name: sum()

Multi-word method name: areaOfCircle()

• It is also possible that a method has the same name as another method name in the same
class, it is known as method overloading.

Types of methods:

• There are two types of methods in java, they are

1.predefined method

2.usre defined method

Predefined method:

• In Java, predefined methods are the method that is already defined in the Java class
libraries is known as predefined methods
• We can directly use these methods just by calling them in the program at any point.

Ex: class hello

public static void main(String args[])

7
System.out.println("hello");

OUTPUT: javac hello.java

Java hello

hello

2.user defined method:

• The method written by the user or programmer is known as a user-defined method.


• These methods are modified according to the requirement.
Ex: import java.util.Scanner;
public class SumOfNumbers
{
public static void main(String args[])
{
int x, y, sum;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the first number: ");
x = sc.nextInt();
System.out.println("Enter the second number: ");
y = sc.nextInt();
sum = sum(x, y);
System.out.println("The sum of two numbers x and y is: " + sum);
}
//method that calculates the sum
public static int sum(int a, int b)
{
int sum = a + b;
return sum;
}

8
}
OUTPUT:
javac SumOfNumbers.java
java SumOfNumbers
Enter the first number: 10
Enter the second number: 20
The sum of two numbers x and y is: 30
DECLARATION OF CLASS OBJECTS:

• Object: it is a basic unit of object oriented programming represents the real life entity.
• An entity that has state and behaviour is known as an entity.
Declaration of an object:

• Declaration of an object is similar to that of variable declaration


• Syntax: name_of_the_class object_reference_name;
• Ex: Student s;
• Here student is the name of the class and “s” is the reference variable which can
represent the object.
• Here a reference variable “s” is declared for an object just to hold the address of an
object.
Initialization of an object:
• When a reference variable is declared, it is necessary to assign physical copy of an
object to that variable.
• This an be done by using “new” keyword.
• After the memory allocation the “new” keyword returns address of memory allocation
to the class.
• Syntax: class name object_reference=new constructor();
• Ex: student s=new student();
• Here, an object can access members of a class using dot(.) operator.
• Syntax: object_referencename.membername;
• Ex: s.id=10;
s.display();

ASSIGNING ONE OBJECT TO ANOTHER:


• We can access another object by using the reference of previous object.
• Here new x() object is created and reference to that object is returned. this reference
gets stored in obj.
• Here the reference of the first object is assigned to the second object.
Ex:
class x
9
{
int a=10;
public static void main(String args[])
{
x obj=new x();
x obj1=obj;
System.out.println(obj.a);
System.out.println(obj1.a);
}
}
OUTPUT: javac x.java
Java x
10
10

Accessing private members of a class:


• The access level of a private member is with in the class only. we cannot access from
out side the class.
• But here we can access the private members out of the class by including public
member.
• Private method should contain at least one public member for access.
Ex:
Class A
{
Private void display()
{
System.out.println(“private method access from outside class”);
}
Public void getdisplay()
{
display();
}
}
10
Class B
{
Public static void main(String args[])
{
A obj=new A();
Obj.getdisplay();
}
}
Output: private method access from outside class

Constructor methods for a class:


• Constructor is a block of code similar to the method.it is called when an instance of the
class is created.
• at the time of calling a constructor, memory for the object is allocated in the memory.
• It is a special type of method which is used to initialize the object.
• If there is no constructor available in the class.in such case, java compiler provides
constructor by default.
• There are 2 types of constructors in java are no-arg constructor and parameterized
constructor.
Ex:
class Student
{
String name;
Int rno;
Student()
{
Name=”hello”;
Rno=12334;
}
Public static void main(String args[])
{
Student s=new student();
System.out.println(s.name);
System.out.println(s.rno);
11
}
}
Output: hello
12334
Constructor overloading:
• Constructor overloading in java can be defined as the concept of having more than one
constructor with different parameters so that every constructor can perform a different
task.
class Constructordemo
{
Constructordemo()
{
System.out.println("constructor with out arguments");
}
Constructordemo(int a)
{
System.out.println("constructor with arguments");
}
}
class Coverload
{
public static void main(String args[])
{
Constructordemo obj=new Constructordemo();
Constructordemo obj1=new Constructordemo(10);
}
}
Output:
constructor with out arguments
constructor with arguments

12
Nested classes:
• In java ,it is possible to define a class within another class, such classes are known as
nested classes.
• They enable you to logically group classes that are only used in one place, thus this
increases the use of encapsulation and create more readable and maintainable code.
• The scope of a nested class is bounded by the scope of its enclosing class.
• A nested class is also a member of its enclosing class.
• Nested classes are divided into two categories:
• 1-static nested class: nested classes that are declared static are called static nested
classes.
• 2-inner class: an inner class is a non-static nested class.
Ex: public class demo
{
Public static void main(string args[])
{
A obj=new A();
A.B obj1=obj.new B();
}
}
Class A
{
Class B
{
Int x=10;
Void display(){
System.out.println(“ helloworld”);
}
}
Output: helloworld.
Passing arguments by value:
• Call by value means that arguments value is copied and is passed to the parameter
list of a method.
• Changes made in a copy of variable never modify the value of variable outside the
function

13
Ex: public class value
{
Int a;
Int b;
Private static void add(int x, int y);
{
X=10;
System.out.println(“result is :”+(x+y));
}
Public static void main(string args[])
{
Value obj=new value();
Obj.a=5;
Obj.b=10;
System.out.println(“before:”+(obj.a+obj.b));
add(obj.a,obj.b);
System.out.println(“after:”+(obj.a+obj.b));
}
}
Output:before:15
Result:20
After:15.

Passing arguments by ref:


• Call by reference means, instead of copying the values of variables, the address of
the variables is used.
• Change in the variable also affects the value of the variable outside the function.
Ex:
public class ref
{
Int a;
Int b;

14
Private static void add(ref obj, ref obj1);
{
Obj.a=10;
System.out.println(“result is :”+(obj.a+obj.b));
}
Public static void main(string args[])
{
ref obj=new ref();
ref obj1=new ref();
Obj.a=5;
Obj.b=10;
System.out.println(“before:”+(obj.a+obj.b));
add(obj, obj);
system.out.println(“after:”+(obj.a+obj.b));
}
}
Output:before:15
Result:20
After:20

Keyword this:
• This can be used to refer current class instance variable.
• This can be used to invoke current class method,constructor.
• This can be passed as an object in the method call, constructor call.
• This can be used to return the current class instance from the method.
Ex:
class This1
{
int a=10;
void display()
{
int a=20;
System.out.println(a);
System.out.println(this.a);
}
public static void main(String args[])

15
{

This1 obj=new This1();


obj.display();
}
}
Output:
javac This1.java
java This1
20
10.

Overloaded Methods :
Method: method is a block of code or collection of statements grouped together to perform a
certain
Task or operation and return the result to the caller if applicable.
Syntax:
accessmodifier returntype method name(parameters)
{
//method body;
}
• When there are multiple functions with the same name but different parameters, then
these functions are said to be overloded.
• Different ways to overload the methods are,
1.by changing the no.of arguments.
2.by changing the data type.
1.by changing the no.of arguments:
• In this example, we have created two methods, first add() method performs addition of
two numbers and second add method performs addition of three numbers.
Ex:

class Adder{
static int add(int a, int b)
{
return a+b;
}
static int add(int a, int b, int c)
{
return a+b+c;

16
}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder. add(10,10));
System.out.println(Adder. add(10,10,10));
}}
Output:20
30
2.by changing the data type:
In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments .
Ex:
class Adder{
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b)
{
return a+b;
}
}
class Overloading
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Output: 22
24.9

17
Overloded constructor methods:
• in Java, we can overload constructors like methods
• The constructor overloading can be defined as the concept of having more than one
constructor with different parameters, so that every constructor can perform a different
task.
Ex:
class Constructordemo
{
Constructordemo()
{
System.out.println("constructor with out arguments");
}
Constructordemo(int a)
{
System.out.println("constructor with arguments");
}
}
class Coverload
{
public static void main(String args[])
{
Constructordemo obj=new Constructordemo();
Constructordemo obj1=new Constructordemo(10);
}
}
Output: constructor with out arguments
constructor with arguments

Class objects as a parameters in methods:


• Java makes it easier to give objects as parameters to methods.
• It is crucial to recognize that sending an object as an argument transmits merely a
reference to the item-not a duplicate of it.

18
• It means that any changes made to the object inside the method will have an immediate
impact on the original object.
Ex:
public class Objectparameter
{
private int a;
private String name;
public Objectparameter(int a, String name)
{
this.a=a;
this.name=name;
}
public void x(Objectparameter p)
{
System.out.println("a"+p.a);
System.out.println("name"+p.name);
}
public static void main(String args[])
{
Objectparameter obj=new Objectparameter(10,"hello");
Objectparameter obj1=new Objectparameter(20,"world");
obj.x(obj1);
}
}
Output:
a20
name world

Recursive methods:
• Recursion is the technique of making a function call itself.
• This technique provides a way to break complicated problems down into simple
problems which are easier to solve.
• Adding two numbers together is easy to do, but adding a range of numbers is more
complicated.
• recursion is used to add a range of numbers together by breaking it down into the simple
task of adding two numbers.
Ex:
public class Recursion1
{
static int a=0;
static void x()
{

19
a++;
if(a<=5)
{
System.out.println("hello" +a);
x();
}
}
public static void main(String args[])
{
x();
}
}
Output:
hello1
hello2
hello3
hello4
hello5

Nesting of methods:
• In Java, methods and variables that are defined within a class can only be accessed by
creating an instance of that class or by using the class name if the methods are static
• The dot operator is used to access methods and variables within a class.
• However, there is an exception to this rule: a method can also be called by another
method using the class name, but only if both methods are present in the same class.
• Efficient code organization and simplified method calls within a class are possible
through nesting of methods.
Syntax:
Class A
{
Method1();
}
Method2()

20
{
Method1();
}
}
Ex:
class Nestedmethod
{
void display()
{
System.out.println("hello");
}
void show()
{
System.out.println("world");
display();
}
public static void main(String args[])
{
Nestedmethod obj=new Nestedmethod();
obj.show();
}
}
Output:
World
Hello.
Overriding methods:
• If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
• In other words, If a subclass provides the specific implementation of the method that
has been declared by one of its parent class, it is known as method overriding.
• Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass

21
• Method overriding is used for runtime polymorphism
Ex:
class A
{
void x()
{
System.out.println("hello");
}
}
class B extends A
{
void x()
{
System.out.println("world");
}
}
class C extends A
{
void x()
{
System.out.println("name");
}
}
class Runtimeploy
{
public static void main(String args[])
{
A obj;
obj=new B();
obj.x();

22
obj=new C();
obj.x();
}
}
Output:
World
Hello.
Attributes final and static:
Static:

• Static keyword in java is used for memory management


• We can apply static keyword with variables, methods, blocks and nested classes.
• The static keyword can be:
1.static variable:
• If you declare any variable as static, it, is known as static variable.
• 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.
• Static variable gets memory only once in the class area at the time of class loading
• It saves memory
2.Static method:

• If you apply any method with static keyword, it is known as static method
• A static method can be invoked without the need for creating an instance of a class.
• A static method can access static data members and can change the value of it.
• There are 2 main restrictions for static methods are:
1.static method cannot use non static data members.
2.this and super keyword cannot be used in static context.
3.Static block:
• it is used to initialize the static data members.
• It is executed before the main method at the time of class loading.
• Executed by default without any explicit call
Nested classes:
• Access with the help of class name
• For single class, we can access directly
Ex:
class A

23
{
static int x=10;
static void display()
{
System.out.println("static method");
}
static
{
System.out.println("static block");
}
}
class Staticdemo
{
public static void main(String args[])
{
System.out.println("main");
System.out.println(A.x);
A.display();
}
}
Output:
main
static block
10
static method
final keyword:
• The final keyword in java is used to restrict the user.
• The java final keyword can be used in many context.
• Final can be applied with the variable, method, class.
• A final variable that have no value it is called blank final variable or un initialized final
variable.
• Final keyword stop value change, stop method overriding, stops inheritance.

24
1.final variable:

• If you make any variable as final,you can change the value of final variable.
Ex:
class A
{
final int x=10;
void display()
{
x=20;
System.out.println(x);
}
public static void main(String args[])
{
A obj=new A();
obj.display();
}
}
Output:compile time error.
2.final method():

• If you make any method as a final, you cannot override it.


Ex:
class A
{
final void display()
{
System.out.println("hello");
}
}
class B extends A
{
void display()
{
System.out.println("world");
}
public static void main(String args[])
{

25
A obj=new A();
obj.display();
}
}
Output:compile time error.
3.final class:

• If you make any class as final, you cannot extend it.


Ex:
final class A
{
void display()
{
System.out.println("hello");
}
}
class B extends A
{
void display()
{
System.out.println("world");
}
public static void main(String args[])
{
A obj=new A();
obj.display();
}
}
Output:
Compile time error.

26

You might also like