Unit 2 Java
Unit 2 Java
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
methodname1(parameter-list)
{ // body of method }
type methodname2(parameter-list)
{ // body of method }
{ // 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
void get()
{ // body
} }
Object in Java
Object is the physical as well as logical entity whereas class is the logical entity
only.
Object Definitions:
1. class Sample{
2. public static void main(String args[]){
3. System.out.println("How are you ");
4. }
5. }
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 −
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.
1. Single-Dimensional Array
2. Multi-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:
}
}
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];
Example:
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.
class Student {
Student(int id, String name) {
System.out.println("Student ID is "+ id + " and name is "+ name );
}
}
}
}
Output:
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.
class Add {
int a;
int b;
Output
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.
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);
}
}
s1.show();
s2.show();
}
}
There are many differences between constructors and methods. They are given below.
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 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.
If you apply static keyword with any method, it is known as static method.
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. }
There can be a lot of usage of java this keyword. In java, this is a reference
variable that refers to the current object.
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
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
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();
Output:
I am green!
I am a Bird
I am black!
I am a Bird
In Multiple Inheritance, a single class inherits from two different superclasses. Multiple Inheritance
for classes is Invalid 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.
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.
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).
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.
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. }}
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.
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. }}
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.
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
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.
1. abstract class A{ }
abstract method
A method that is declared as abstract and does not have implementation is
known as abstract method.
In this example, Bike the abstract class that contains only one abstract method
run. It implementation is provided by the Honda class.
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?
There are mainly three reasons to use interface. They are given below.
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.
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. }}