0% found this document useful (0 votes)
21 views19 pages

Java 2

The document provides an overview of classes and objects in Java, including syntax for declaring classes, creating objects, and defining methods. It explains concepts such as instance variables, method overloading, constructors, and Java naming conventions, along with examples for clarity. Additionally, it highlights the differences between classes and objects, and between constructors and methods.
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)
21 views19 pages

Java 2

The document provides an overview of classes and objects in Java, including syntax for declaring classes, creating objects, and defining methods. It explains concepts such as instance variables, method overloading, constructors, and Java naming conventions, along with examples for clarity. Additionally, it highlights the differences between classes and objects, and between constructors and methods.
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

Syntax to declare a class:

class <class_name>{

data member;

method;

Simple Example of Object and Class

In this example, we have created a Student class that has two data members’ id and name. We
are creating the object of the Student class by new keyword and printing the objects value.

class Student1{

int id;//data member (also instance variable)

String name;//data member(also instance variable)

public static void main(String args[]){

Student1 s1=new Student1();//creating an object of Student

[Link]([Link]);

[Link]([Link]);

Output:0 null

Instance variable in Java

A variable that is created inside the class but outside the method is known as instance variable.
Instance variable doesn't get memory at compile time. It gets memory at runtime when object
(instance) is created. That is why, it is known as instance variable.

Method in Java

In java, a method is like function i.e. used to expose behaviour of an object.

1
Advantage of Method

 Code Reusability
 Code Optimization

new keyword

The new keyword is used to allocate memory at runtime.

Example of Object and class that maintains the records of students

In this example, we are creating the two objects of Student class and initializing the value to
these objects by invoking the insertRecord method on it. Here, we are displaying the state (data)
of the objects by invoking the displayInformation method.

class Student2{

int rollno;

String name;

void insertRecord(int r, String n){ //method

rollno=r;

name=n;

void displayInformation(){[Link](rollno+" "+name);}//method

public static void main(String args[]){

Student2 s1=new Student2();

Student2 s2=new Student2();

[Link](111,"Karan");

[Link](222,"Aryan");

[Link]();

[Link]();

2
Output:

111 Karan

222 Aryan

As you see in the above figure, object gets the memory in Heap area and reference variable refers
to the object allocated in the Heap memory area. Here, s1 and s2 both are reference variables that
refer to the objects allocated in memory.

Another Example of Object and Class

There is given another example that maintains the records of Rectangle class. Its exaplanation is
same as in the above Student class example.

class Rectangle{

int length;

int width;

void insert(int l,int w){

length=l;

width=w;

3
}

void calculateArea(){[Link](length*width);}

public static void main(String args[]){

Rectangle r1=new Rectangle();

Rectangle r2=new Rectangle();

[Link](11,5);

[Link](3,15);

[Link]();

[Link]();

Output: 55

45

What are the different ways to create an object in Java?

There are many ways to create an object in java. They are:

 By new keyword
 By newInstance() method
 By clone() method
 By factory method etc.

We will learn, these ways to create the object later.

Creating multiple objects by one type only

We can create multiple objects by one type only as we do in case of primitives.


Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects

4
Difference between object and class

There are many differences between object and class. A list of differences between object and
class are given below:

Object

 Object is an instance of a class.


 Object is a real world entity such as pen, laptop, mobile, bed, keyboard, mouse, chair etc.
 Object is a physical entity.
 Object is created through new keyword mainly e.g. Student s1=new Student();
 Object is created many times as per requirement.
 Object allocates memory when it is created.
 There are many ways to create object in java such as new keyword, newInstance()
method, clone() method, factory method and deserialization.

Class

 Class is a blueprint or template from which objects are created.


 Class is a group of similar objects.
 Class is a logical entity.
 Class is declared using class keyword e.g. class Student{}
 Class is declared once.
 Class doesn't allocated memory when it is created.
 There is only one way to define class in java using class keyword.

Java naming conventions

Java naming convention is a rule to follow as you decide what to name your identifiers such as
class, package, variable, constant, method etc.

But, it is not forced to follow. So, it is known as convention not rule.

All the classes, interfaces, packages, methods and fields of java programming language are given
according to java naming convention.

Advantage of naming conventions in java

By using standard Java naming conventions, you make your code easier to read for yourself and
for other programmers. Readability of Java program is very important. It indicates that less time
is spent to figure out what the code does.

5
Java naming conventions are given below:

 class name: should start with uppercase letter and be a noun e.g. String, Color, Button,
System, Thread etc.
 interface name: should start with uppercase letter and be an adjective e.g. Runnable,
Remote, ActionListener etc.
 method name: should start with lowercase letter and be a verb e.g. actionPerformed(),
main(), print(), println() etc.
 variable name: should start with lowercase letter e.g. firstName, orderNumber etc.
 package name: should be in lowercase letter e.g. java, lang, sql, util etc.
 constants name: should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY
etc.

CamelCase in java naming conventions

java follows camelcase syntax for naming the class, interface, method and variable.

If name is combined with two words, second word will start with uppercase letter always e.g.
actionPerformed(), firstName, ActionEvent, ActionListener etc.

6
Method Overloading in Java

 Different ways to overload the method


 By changing the no. of arguments
 By changing the datatype
 Why method overloading is not possible by changing the return type
 Can we overload the main method
 method overloading with Type Promotion

If a class has multiple methods by same name but different parameters, it is known as Method
Overloading.

If we have to perform only one operation, having same name of the methods increases the
readability of the program.

Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand the
behaviour of the method because its name differs. So, we perform method overloading to figure
out the program quickly.

Advantage of method overloading?

 Method overloading increases the readability of the program.

7
Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

In java, Method Overloading is not possible by changing the return type of the method.

1) Example of Method Overloading by changing the no. of arguments

In this example, we have created two overloaded methods, first sum method performs addition of
two numbers and second sum method performs addition of three numbers.

class Calculation{

void sum(int a,int b){[Link](a+b);}

void sum(int a,int b,int c){[Link](a+b+c);}

public static void main(String args[]){

Calculation obj=new Calculation();

[Link](10,10,10);

[Link](20,20);

Output: 30

40

8
2) Example of Method Overloading by changing data type of argument

In this example, we have created two overloaded methods that differs in data type. The first sum
method receives two integer arguments and second sum method receives two double arguments.

class Calculation2{

void sum(int a,int b){[Link](a+b);}

void sum(double a,double b){[Link](a+b);}

public static void main(String args[]){

Calculation2 obj=new Calculation2();

[Link](10.5,10.5);

[Link](20,20);

Output: 21.0

40

Why Method Overloading is not possible by changing the return type of method?

In java, method overloading is not possible by changing the return type of the method because
there may occur ambiguity. Let's see how ambiguity may occur:

Because there was problem:

class Calculation3{

int sum(int a,int b){[Link](a+b);}

double sum(int a,int b){[Link](a+b);}

public static void main(String args[]){

Calculation3 obj=new Calculation3();

int result=[Link](20,20); //Compile Time Error

9
}

Output:

int result=[Link](20,20); //Here how can java determine which sum() method should be called

Can we overload main() method?

Yes, by method overloading. You can have any number of main methods in a class by method
overloading. Let's see the simple example:

class Overloading1{

public static void main(int a){

[Link](a);

public static void main(String args[]){

[Link]("main() method invoked");

main(10);

Output: main() method invoked

10

Method Overloading and TypePromotion

One type is promoted to another implicitly if no matching datatype is found. Let's understand the
concept by the figure given below.

10
As displayed in the above diagram, byte can be promoted to short, int, long, float or double. The
short datatype can be promoted to int,long,float or double. The char datatype can be promoted to
int,long,float or double and so on.

Example of Method Overloading with TypePromotion

1. class OverloadingCalculation1{
2. void sum(int a,long b){[Link](a+b);}
3. void sum(int a,int b,int c){[Link](a+b+c);}
4.
5. public static void main(String args[]){
6. OverloadingCalculation1 obj=new OverloadingCalculation1();
7. [Link](20,20);//now second int literal will be promoted to long
8. [Link](20,20,20);
9.
10. }
11. }
Output: 40
60

11
Example of Method Overloading with TypePromotion if matching found

If there are matching type arguments in the method, type promotion is not performed.

1. class OverloadingCalculation2{
2. void sum(int a,int b){[Link]("int arg method invoked");}
3. void sum(long a,long b){[Link]("long arg method invoked");}
4.
5. public static void main(String args[]){
6. OverloadingCalculation2 obj=new OverloadingCalculation2();
7. [Link](20,20);//now int arg sum() method gets invoked
8. }
9. }

Output: int arg method invoked

Example of Method Overloading with TypePromotion in case ambiguity

If there are no matching type arguments in the method, and each method promotes similar
number of arguments, there will be ambiguity.

1. class OverloadingCalculation3{
2. void sum(int a,long b){[Link]("a method invoked");}
3. void sum(long a,int b){[Link]("b method invoked");}
4.
5. public static void main(String args[]){
6. OverloadingCalculation3 obj=new OverloadingCalculation3();
7. [Link](20,20);//now ambiguity
8. }
9. }
Output: Compile Time Error

One type is not de-promoted implicitly for example double cannot be de-promoted to any
type implicitly.

12
Constructor in Java

 Types of constructors
 Default Constructor
 Parameterized Constructor
 Constructor Overloading
 Does constructor return any value
 Copying the values of one object into another
 Does constructor perform other task instead initialization

Constructor in java is a special type of method that is used to initialize the object. Java
constructor is invoked at the time of object creation. It constructs the values i.e. provides data for
the object that is why it is known as constructor.

Rules for creating java constructor

There are basically two rules defined for the constructor.

1. Constructor name must be same as its class name


2. Constructor must have no explicit return type

Types of java constructors

There are two types of constructors:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

13
Java Default Constructor
A constructor that has no parameter is known as default constructor.

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 creation.

1. class Bike1{
2. Bike1(){[Link]("Bike is created");}
3. public static void main(String args[]){
4. Bike1 b=new Bike1();
5. }
6. }

Output: Bike is created

Rule: If there is no constructor in a class, compiler automatically creates a default


constructor.

Q) What is the purpose of default constructor?

Default constructor provides the default values to the object like 0, null etc. depending on the
type.

14
Example of default constructor that displays the default values

1. class Student3{
2. int id;
3. String name;
4.
5. void display(){[Link](id+" "+name);}
6.
7. public static void main(String args[]){
8. Student3 s1=new Student3();
9. Student3 s2=new Student3();
10. [Link]();
11. [Link]();
12. }
13. }

Output:
0 null
0 null

Explanation:In the above class,you are not creating any constructor so compiler provides you a
default [Link] 0 and null values are provided by default constructor.

Java parameterized constructor

A constructor that has parameters is known as parameterized constructor.

Why use parameterized constructor?

Parameterized constructor is used to provide different values to the distinct objects.

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.

1. class Student4{
2. int id;
3. String name;

15
4.
5. Student4(int i,String n){
6. id = i;
7. name = n;
8. }
9. void display(){[Link](id+" "+name);}
10.
11. public static void main(String args[]){
12. Student4 s1 = new Student4(111,"Karan");
13. Student4 s2 = new Student4(222,"Aryan");
14. [Link]();
15. [Link]();
16. }
17. }

Output:

111 Karan
222 Aryan

Constructor Overloading in Java


Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists. The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.

Example of Constructor Overloading

1. class Student5{
2. int id;
3. String name;
4. int age;
5. Student5(int i,String n){
6. id = i;
7. name = n;
8. }
9. Student5(int i,String n,int a){
10. id = i;
11. name = n;
12. age=a;
13. }
14. void display(){[Link](id+" "+name+" "+age);}

16
15.
16. public static void main(String args[]){
17. Student5 s1 = new Student5(111,"Karan");
18. Student5 s2 = new Student5(222,"Aryan",25);
19. [Link]();
20. [Link]();
21. }
22. }

Output:

111 Karan 0
222 Aryan 25

Difference between constructor and method in Java

There are many differences between constructor and method. They are listed below.

Java constructor

 Constructor is used to initialize the state of an object.


 Constructor must not have return type.
 Constructor is invoked implicitly.
 The java compiler provides a default constructor if you don't have any constructor.
 Constructor name must be same as the class name.

Java method

 Method is used to expose behaviour of an object


 Method must have return type
 Method is invoked explicitly.
 Method is not provided by compiler in any case.
 Method name may or may not be same as class name.

17
Java Copy Constructor

There is no copy constructor in java. But, we can copy the values of one object to another like
copy constructor in C++.

There are many ways to copy the values of one object into another in java. They are:

 By constructor
 By assigning the values of one object into another
 By clone() method of Object class

In this example, we are going to copy the values of one object into another using java
constructor.

1. class Student6{
2. int id;
3. String name;
4. Student6(int i,String n){
5. id = i;
6. name = n;
7. }
8.
9. Student6(Student6 s){
10. id = [Link];
11. name =[Link];
12. }
13. void display(){[Link](id+" "+name);}
14.
15. public static void main(String args[]){
16. Student6 s1 = new Student6(111,"Karan");
17. Student6 s2 = new Student6(s1);
18. [Link]();
19. [Link]();
20. }
21. }

Output:

111 Karan
111 Karan

18
Copying values without constructor

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.

1. class Student7{
2. int id;
3. String name;
4. Student7(int i,String n){
5. id = i;
6. name = n;
7. }
8. Student7(){}
9. void display(){[Link](id+" "+name);}
10.
11. public static void main(String args[]){
12. Student7 s1 = new Student7(111,"Karan");
13. Student7 s2 = new Student7();
14. [Link]=[Link];
15. [Link]=[Link];
16. [Link]();
17. [Link]();
18. }
19. }

Output:

111 Karan
111 Karan

Does constructor return any value?

Yes, that is current class instance (You cannot use return type yet it returns a value).

Can constructor perform other tasks instead of initialization?

Yes, like object creation, starting a thread, calling method etc. You can perform any operation in
the constructor as you perform in the method.

19

You might also like