0% found this document useful (0 votes)
17 views24 pages

Unit 2 Java

The document provides an overview of Java programming concepts including classes, objects, methods, and arrays. It explains the structure of classes, the characteristics of objects, and the use of methods for behavior. Additionally, it covers Java identifiers, modifiers, constructors, static keywords, and inheritance, emphasizing their roles in Java programming.

Uploaded by

Rohit
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)
17 views24 pages

Unit 2 Java

The document provides an overview of Java programming concepts including classes, objects, methods, and arrays. It explains the structure of classes, the characteristics of objects, and the use of methods for behavior. Additionally, it covers Java identifiers, modifiers, constructors, static keywords, and inheritance, emphasizing their roles in Java programming.

Uploaded by

Rohit
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/ 24

I.

CLASS, OBJECT AND METHODS

Java program is a collection of objects that communicate via invoking each other's
methods. We now briefly look into class, object, methods, and instance variables.
Class − A class can be defined as a template/blueprint that describes the behavior/state that the
object of its type supports.

A class is declared by use of the class keyword. A simplified general form of a class
definition is shown here:

class classname

type instance-variable1; type instance-variable2;

// ... type instance-variableN; type

methodname1(parameter-list)

{ // body of method }

type methodname2(parameter-list)

{ // body of method }

// ... type methodnameN(parameter-list)

{ // body of method } }

The data, or variables, defined within a class are called instance variables. The code
is contained within methods. Collectively, the methods and variables defined within
a class are called members of the class. In most classes, the instance variables are acted
upon and accessed by the methods defined for that class

Simple Class

Class Sample

int len, float ht

void get()

{ // body
} }

Here a class Sample contains two variable len and ht

Object in Java

Object is the physical as well as logical entity whereas class is the logical entity
only.

An object has three characteristics:

 state: represents data (value) of an object.


 behavior: represents the behavior (functionality) of an object such as deposit,
withdraw etc.
 identity: Object identity is typically implemented via a unique ID. The value of
the ID is not visible to the external user. But, it is used internally by the JVM
to identify each object uniquely.

Object is an instance of a class. Class is a template or blueprint from which


objects are created. So object is the instance(result) of a class.

Object Definitions:

 Object is a real world entity. Object is a run time entity.


 Object is an entity which has state and behavior.
 Object is an instance of a class.

Sample s=new Sample() here s is an object for the class Sample

new operator is used to create an object

Methods − A method is basically a behavior. A class can contain many methods. It is in


methods where the logics are written, data is manipulated and all the actions are
executed.

Let's create the Simple java program:

1. class Sample{
2. public static void main(String args[]){
3. System.out.println("How are you ");
4. }
5. }

save this file as Sample.java


To compile: javac Sample.java

To execute: java Sample

Java Identifiers

All Java components require names. Names used for classes, variables, and
methods are called identifiers.

In Java, there are several points to remember about identifiers. They are as
follows −

 All identifiers should begin with a letter (A to Z or a to z), currency


character ($) or an underscore (_).
 After the first character, identifiers can have any combination of
characters.
 A key word cannot be used as an identifier.
 Most importantly, identifiers are case sensitive.
 Examples of legal identifiers: age, $salary, _value, 1_value.
 Examples of illegal identifiers: 123abc, -salary.

Java Modifiers: There are two categories of modifiers −

 Access Modifiers − default, public , protected, private


 Non-access Modifiers − final, abstract, strictfp

Arrays

Arrays in Java are non-primitive data types that store elements of a similar data type in the
memory. Arrays in Java can store both primitive and non-primitive types of data in it.

Types of Array in Java

In Java, there are two types of arrays:

1. Single-Dimensional Array
2. Multi-Dimensional Array

1. Single Dimensional Array

An array that has only one subscript or one dimension is known as a single-dimensional array. It is
just a list of the same data type variables.

One dimensional array can be of either one row and multiple columns or multiple rows and one
column. For instance, a student's marks in five subjects indicate a single-dimensional array.
Example:

public class Demo {


public static void main (String[] args) {
// declaring and initializing an array
String strArray[] = {"Python", "Java", "C++", "C", "PHP"};

// using a for-each loop for printing the array


for(String i : strArray) {
System.out.print(i + " ");
}

// find the length of an array


System.out.println("\nLength of array: "+strArray.length);

}
}

2. Multi-Dimensional Array

In not all cases, we implement a single-dimensional array. Sometimes, we are required to create an
array within an array.

int marks[][] = {
{77,85,68,99,87},
{98,56,79,90,92},
{78,88,56,70,99}
};
OR
int marks[][] = new int[3][5];

// both will create a 2D array with 3 rows and 5 columns.

public class Simple2DArray {


public static void main(String[] args) {
// Declare and initialize a 2D array
int[][] numbers = {
{1, 2, 3},
{4, 5, 6}
};

// Print the 2D array


System.out.println("2D Array:");
for (int i = 0; i < 2; i++) { // 2 rows
for (int j = 0; j < 3; j++) { // 3 columns
System.out.print(numbers[i][j] + " ");
}
System.out.println(); // Move to the next line after each row
}
}
}
Arrays of Objects
As the name suggests, an array of objects is nothing but a list of objects stored in the array. Notice
that it does not store objects in an array but stores the reference variable of that object. The syntax
will be the same as above.

Example:

Student studentObj[] = new Student[3];

After the above statement executes, it will create an array of objects of the Student class with a length
of 3 studentObj references. For each object reference, we need to implement an object using new.

Let’s understand it more clearly with a Java program.

class Student {
Student(int id, String name) {
System.out.println("Student ID is "+ id + " and name is "+ name );
}
}

public class Test {


public static void main (String[] args) {
// declaring an array of Object
Student obj[] = new Student[3];

obj[0] = new Student(1,"Bharat");


obj[1] = new Student(5,"Vivaan");
obj[2] = new Student(6,"Smith");

}
}

Output:

Student ID is 1 and name is Bharat


Student ID is 5 and name is Vivaan
Student ID is 6 and name is Smith

Object as an Parameter
Object as an argument is use to establish communication between two or more objects of same
class as well as different class, i.e, user can easily process data of two same or different objects
within function.
By Abhishek Jain Last updated : January 14, 2024
In Java, When a primitive type is passed to a method ,it is done by use of call-by-value . Objects are
implicitly passed by use of call-by-reference.

This means when we pass primitive data types to method it will pass only values to function
parameters so any change made in parameter will not affect the value of actual parameters.

Whereas Objects in java are reference variables, so for objects a value which is the reference to the
object is passed. Hence the whole object is not passed but its referenced gets passed. All modification
to the object in the method would modify the object in the Heap.

Passing Object as Parameter in Function

class Add {
int a;
int b;

Add(int x, int y) // parametrized constructor


{
a = x;
b = y;
}
void sum(Add A1) // object 'A1' passed as parameter in function 'sum'
{
int sum1 = A1.a + A1.b;
System.out.println("Sum of a and b :" + sum1);
}
}

public class Main {


public static void main(String arg[]) {
Add A = new Add(5, 8);
/* Calls the parametrized constructor
with set of parameters*/
A.sum(A);
}
}

Output

Sum of a and b :13

CONSTRUCTORS

Constructor is special member function ,it has the same name as class name.
It is called when an instance of object is created and memory is allocated for the
object.

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


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 in java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor
3. Copy Constructor

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

class
Sample{ Sa
mple()
{
System.out.println("Sample is created");
}
public static void main(String args[])
{
Sample b=new Sample();
} }

Parameterized constructor
A constructor which has a specific number of parameters is
called parameterized constructor.
1. class Student4{
2. int id;
3. String name;
4. Student4(int i,String n){
5. id = i;
6. name = n;
7. }
8. void display(){System.out.println(id+" "+name);} 9.
10. public static void main(String args[]){
11. Student4 s1 = new Student4(111,"Karan");
12. Student4 s2 = new Student4(222,"Aryan");
13. s1.display();
14. s2.display();
15. }
16. }

Copy constructor

Unlike other constructors copy constructor is passed with another object which copies the
data available from the passed object to the newly created object.

class Student {
int id;
String name;

// Constructor
Student(int i, String n) {
id = i;
name = n;
}

// Copy constructor
Student(Student s) {
id = s.id;
name = s.name;
}

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

public class Main {


public static void main(String[] args) {
Student s1 = new Student(101, "Dev");
Student s2 = new Student(s1); // Copy constructor

s1.show();
s2.show();
}
}

Difference between constructor and method in java

There are many differences between constructors and methods. They are given below.

Java Constructor Java Method


Constructor is used to initialize the state of an Method is used to expose
object. behaviour of an object.
Method must have return
Constructor must not have return type.
type.
Constructor is invoked implicitly. Method is invoked explicitly.
The java compiler provides a default constructor if
Method is not provided by
you don't have any constructor.
compiler in any case.
Constructor name must be same as the class Method name may or may not be
name. same as class name.

Java static keyword

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

The static can be:

1. variable (also known as class variable)


2. method (also known as class method)
3. block
4. nested class

1) Java static variable

If you declare any variable as static, it is known static variable.

 The static variable can be used to refer the common property of all objects (that
is not unique for each object) e.g. company name of employees,college name of
students etc.
 The static variable gets memory only once in class area at the time of class loading.

Advantage of static variable: It makes your program memory


efficient (i.e it saves memory).
class Stud{ int
rollno; String
name;
static String college ="ITS";
Stud(int r,String n){
rollno = r; name
= n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String


args[]){ Stud s1 = new
Stud(11,"Krishna"); Stud s2 = new
Stud(22,"Rama"); s1.display();
s2.display();
} }

2) Java static method

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

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


 A static method can be invoked without the need for creating an
instance of a class.
 static method can access static data member and can change the value of
it.

Example of static method


1. //Program of changing the common property of all objects(static field).

2.
3. class Stud{
4. int rollno;
5. String name;
6. static String college = "BEC"; 7.
8. static void change(){
9. college = "JBIEIT";
10. }
11. Stud(int r, String n){
12. rollno = r;
13. name = n;
14. }
15.
16. void display (){System.out.println(rollno+" "+name+" "+college
);}
17. public static void main(String args[]){
18. Stud.change();
19. Stud s1 = new Stud (11,"Kiran");
20. Stud s2 = new Stud (22,"Arjun");
21. Stud s3 = new Stud (33,"srinu");
22. s1.display();
23. s2.display();
24. s3.display();
25. }
26. }

this keyword in java

There can be a lot of usage of java this keyword. In java, this is a reference
variable that refers to the current object.

Usage of java this keyword

Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

1) this: to refer current class instance variable


The this keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, this keyword resolves the problem of
ambiguity.

class
Student{ int
rollno; String
name; float fee;
Student(int rollno,String name,float
fee){ this.rollno=rollno;
this.name=name; this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){ Student
s1=new Student(111,"ankit",5000f); Student
s2=new Student(112,"sumit",6000f); s1.display();
s2.display(); }}
Inheritance

Inheritance can be defined as the procedure or mechanism of acquiring all the


properties and behavior of one class to another, i.e. acquiring the properties and
behavior of child class from the parent class. This concept was built in order to achieve
the advantage of creating a new class that gets built upon an already existing class(es). It
is mainly used for code reusability within a Java program. The class that gets inherited
taking the properties of another class is the subclass or derived class or child class. Again,
the class whose properties get inherited is the superclass or base class or parent class.
The keyword extends is used to inherit the properties of the base class to derived
class. The structure of using this keyword looks something like this:

class base
{
.....
.....
}
class derive extends base
{
.....
.....
}

Inheritance concept
Subclass

A subclass, also known as child class or derived class, inherits another class's properties and
behaviourss. So, if A and B are two classes and if B class inherits A class, then the B class is called
the subclass.

Superclass

A superclass, also known as parent class or base class, is the class whose properties and behaviors
are inherited by the subclass. So, if A and B are two classes and if B class inherits A class, then A
class is called the superclass.
1. Single Inheritance in Java

This is the simplest form of inheritance, where one class inherits another class.

class Bird {
void fly() {
System.out.println("I am a Bird");
}
}
// Inheriting SuperClass to SubClass
class Parrot extends Bird {
void whatColourAmI() {
System.out.println("I am green!");
}
}
class Main {
public static void main(String args[]) {
Parrot obj = new Parrot();
obj.whatColourAmI();
obj.fly();
}
}

Output:
I am green!
I am a Bird
2. Multilevel Inheritance in Java

This is an extension to single inheritance in Java, where another class again inherits the subclass,
which inherits the superclass.

In this type of inheritance, a derived class gets created from another derived class and
can have any number of levels.

class Bird {
void fly() {
System.out.println("I am a Bird");
}
}
// Inheriting class Bird
class Parrot extends Bird {
void whatColourAmI() {
System.out.println("I am green!");
}
}
// Inheriting class Parrot
class SingingParrot extends Parrot {
void whatCanISing() {
System.out.println("I can sing Opera!");
}
}
class Main {
public static void main(String args[]) {
SingingParrot obj = new SingingParrot();
obj.whatCanISing();
obj.whatColourAmI();
obj.fly();
}
}

Output:
I can sing Opera!
I am green!
I am a Bird

3. Hierarchical Inheritance in Java

In Hierarchical inheritance, a single superclass is inherited separately by two or more subclasses. The
figure below illustrates this inheritance:

class Bird {
void fly() {
System.out.println("I am a Bird");
}
}
class Parrot extends Bird {
void whatColourAmI() {
System.out.println("I am green!");
}
}
class Crow extends Bird {
void whatColourAmI() {
System.out.println("I am black!");
}
}
class Main {
public static void main(String args[]) {
Parrot par = new Parrot();
Crow cro = new Crow();
//Call methods of Parrot Class
par.whatColourAmI();
par.fly();

//Call methods of Crow Class


cro.whatColourAmI();
cro.fly();
}
}

Output:
I am green!
I am a Bird
I am black!
I am a Bird

4. Multiple Inheritance in Java

In Multiple Inheritance, a single class inherits from two different superclasses. Multiple Inheritance
for classes is Invalid in Java.

5. Hybrid Inheritance in Java

Hybrid inheritance is a combination of hierarchical inheritance and multiple inheritance. This is also
not possible and is Invalid in Java. The figure below illustrates hybrid inheritance in Java.
VIII Polymorphism

The word polymorphism means having multiple forms. The term Polymorphism gets
derived from the Greek word where poly + morphos where poly means many and
morphos means forms.

Polymorphism is another special feature of object-oriented programming (OOPs). The


approach which lies beneath this concept is "single interface with multiple
implementations." This offers a single interface for controlling access to a general class
of actions.

Polymorphism can be achieved in two of the following ways:

 Method Overloading(Compile time Polymorphism)


 Method Overriding(Run time Polymorphism)

 Static Polymorphism is in other words termed as compile-time binding or early


binding.
 Static binding occurs at compile time. Method overloading is a case of static
binding and in this case binding of method call to its definition happens at the time
of compilation.

 To call an overloaded method in Java, it is must use the type and/or the number
of arguments to determine which version of the overloaded method to actually
call.
 The overloaded methods may have varied return types and the return type single-
handedly is insufficient to make out two versions of a method.
 As and when Java compiler encounters a call to an overloaded method, it simply
executes the version of the method whose parameters match the arguments used
in the call.
 It permits the user to obtain compile time polymorphism with name method
name.
 An overloaded method is able to throw different kinds of exceptions.
 A method which is overloaded can contain different access modifiers.

Overloading method's argument lists might differ in:

 Number of parameters passed


 Data type of actual parameters
 Sequence of data type of actual parameters
class Mltply {
void mul(int a, int b) { System.out.println("Sum
of two=" + (a * b));
}

void mul(int a, int b, int c) { System.out.println("Sum of


three=" + (a * b * c));
}
}
class Polymorphism {
public static void main(String args[])
{ Mltply m = new Mltply();
m.mul(6, 10);
m.mul(10, 6, 5);
} }

Rules to method overriding

 Argument list: The argument list at the time of overriding method need to be
same as that of the method of the parent class. The data types of the arguments
along with their sequence must have to be preserved as it is in the overriding
method.
 Access Modifier: The Access Modifier present in the overriding method
(method of subclass) cannot be more restrictive than that of an overridden
method of the parent class.
 The private, static and final methods can't be overridden as they are local to the
class.
 Any method which is overriding is able to throw any unchecked exceptions, in
spite of whether the overridden method usually method of parent class might
throw an exception or not.

//method overriding
class parent {
public void work() {
System.out.println("Parent is under retirement from work.");
}
}
class child extends parent
{ public void work() {
System.out.println("Child has a job");
System.out.println(" He is doing it well");
}
public static void main(String argu[])
{ child c1 = new child();
c1.work();
} }
Advantage of method overriding

One major advantage of method overriding is that a class can give its own specific
execution to an inherited method without having the modification in the parent class
(base class).

super keyword in java

The super keyword in java is a reference variable which is used to refer immediate parent
class object.

Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.

Usage of java super Keyword

1. super can be used to refer immediate parent class instance variable.


2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

1) super is used to refer immediate parent class instance variable.

We can use super keyword to access the data member or field of parent class. It is
used if parent class and child class have same fields.

1. class Animal{
2. String color="white";
3. }
4. class Dog extends Animal{
5. String color="black";
6. void printColor(){
7. System.out.println(color);//prints color of Dog class
8. System.out.println(super.color);//prints color of Animal class
9. }
10. }
11. class TestSuper1{
12. public static void main(String args[]){
13. Dog d=new Dog();
14. d.printColor();
15. }}

Method Overloading in Java

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

Advantage of method overloading


Method overloading increases the readability of the program.

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

1) Method Overloading: changing 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.

In this example, we are creating static methods so that we don't need to create instance
for calling methods.

1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
5. class TestOverloading1{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
9. }}

2) Method Overloading: changing data type of arguments

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.

1. class Adder{
2. static int add(int a, int b){return a+b;}
3. static double add(double a, double b){return a+b;}
4. }
5. class TestOverloading2{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(12.3,12.6));
9. }}
Method Overriding in Java

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 subclass provides the specific implementation of the method that
has been provided by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

 Method overriding is used to provide specific implementation of a method


that is already provided by its super class.
 Method overriding is used for runtime polymorphism Rules

for Java Method Overriding

1. method must have same name as in the parent class


2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).

1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. class Bike2 extends Vehicle{
5. void run(){System.out.println("Bike is running safely");} 6.
7. public static void main(String args[]){
8. Bike2 obj = new Bike2();
9. obj.run();
10. }

ABSTRACTION

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only


functionality to the user.

Another way, it shows only important things to the user and hides the internal details
for example sending sms, you just type the text and send the message. You don't know
the internal processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class in Java


A class that is declared as abstract is known as abstract class. It needs to be
extended and its method implemented. It cannot be instantiated.

Example abstract class

1. abstract class A{ }

abstract method
A method that is declared as abstract and does not have implementation is
known as abstract method.

Example abstract method

1. abstract void printStatus();//no body and abstract

Example of abstract class that has abstract method

In this example, Bike the abstract class that contains only one abstract method
run. It implementation is provided by the Honda class.

1. abstract class Bike{


2. abstract void run();
3. }
4. class Honda4 extends Bike{
5. void run(){System.out.println("running safely..");}
6. public static void main(String args[]){
7. Bike obj = new Honda4();
8. obj.run();
9. }
10. }

1. abstract class Shape{


2. abstract void draw();
3. }
4. //In real scenario, implementation is provided by others i.e. unknown by end
user
5. class Rectangle extends Shape{
6. void draw(){System.out.println("drawing rectangle");}
7. }
8. class Circle1 extends Shape{
9. void draw(){System.out.println("drawing circle");}
10. }
11. //In real scenario, method is called by programmer or user
12. class TestAbstraction1{
13. public static void main(String args[]){
14. Shape s=new Circle1();//In real scenario, object is provided thro ugh method
e.g. getShape() method
15. s.draw();
16. }
17. }

Interface in Java

An interface in java is a blueprint of a class. It has static constants and abstract methods.

The interface in java is a mechanism to achieve abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve abstraction and
multiple inheritance in Java.

Java Interface also represents IS-A relationship. It

cannot be instantiated just like abstract class. Why use

Java interface?

There are mainly three reasons to use interface. They are given below.

 It is used to achieve abstraction.


 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling

Java Interface Example

In this example, Printable interface has only one method, its implementation is
provided in the A class.

1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");} 6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }

Differences between abstract class and interface that are given below.

Abstract class Interface


1) Abstract class can have abstract and Interface can have only abstract methods. Since
non-abstract methods. Java 8, it can have default and static methods
also.
2) Abstract class doesn't support
Interface supports multiple inheritance.
multiple inheritance.
3) Abstract class can have final, Interface has only static and final
non-final, static and non-static variables.
variables.
4) Abstract class can provide the Interface can't provide the
implementation of interface. implementation of abstract class.
5) The abstract keyword is used to The interface keyword is used to declare
declare abstract class. interface.
6)Example: Example:
public abstract class public interface
Shape{ public abstract Drawable{ void
void draw(); draw();
} }

1. interface A{
2. void a(); void b();
3. void c(); void d();
4. }
5. abstract class B implements A{
6. public void c(){System.out.println("I am c");}
7. }
8. class M extends B{
9. public void a(){System.out.println("I am a");}
10. public void b(){System.out.println("I am b");}
11. public void d(){System.out.println("I am d");}
12. }
13. class Test5{
14. public static void main(String args[]){
15. A a=new M();
16. a.a();
17. a.b();
18. a.c();
19. a.d();
20. }}

You might also like