Java Unit 2
Java Unit 2
Java Unit 2
Object in Java
An entity that has state and behaviour is known as an object
e.g., chair, bike, marker, pen, table, car, etc.
It can be physical or logical (tangible and intangible).
The example of an intangible object is the banking system.
For Example,
Pen is an object.
Its name is Reynolds;
color is white, known as its state.
It is used to write, so writing is its behavior.
Object Definitions:
An object is a real-world entity.
An object is a runtime entity.
The object is an entity which has state and behaviour.
The object is an instance of a class.
Class in Java
A class is a group of objects which have common properties.
It is a template or blueprint from which objects are created.
It is a logical entity.
It can't be physical.
class <class_name>
{
field;
method;
}
Method in Java
In Java, a method is like a function which is used to expose the behaviour of an object.
Advantage of Method
Code Reusability
Code Optimization
In real time development, we create classes and use it from another class.
It is a better approach than previous one.
class Student
{
int id;
String name;
}
class TestStudent2
{
public static void main(String args[])
{
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name); //printing members with a white space
} }
Example 2: create multiple objects and store information in it through reference variable.
class Student
{
int id;
String name;
}
class TestStudent3{
public static void main(String args[])
{
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
s1.id=101;
s1.name="Sonoo";
s2.id=102;
s2.name="Amit";
//Printing data
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
}
}
we are creating the two objects of Student class and initializing the value to these objects by
invoking the insertRecord method.
we are displaying the state (data) of the objects by invoking the displayInformation() method.
class Student
{
int rollno;
String name;
void insertRecord(int r, String n)
{
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation(); } }
Object gets the memory in heap memory area.
The reference variable refers to the object allocated in the heap memory area.
s1 and s2 both are reference variables that refer to the objects allocated in memory.
Example1:
class Employee
{
int id;
String name;
float salary;
void insert(int i, String n, float s)
{
id=i;
name=n;
salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}
}
Example 2:
class Rectangle
{
int length;
int width;
void insert(int l, int w)
{
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle1
{
public static void main(String args[])
{
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
class Account
{
int acc_no;
String name;
float amount;
//Method to initialize object
void insert(int a,String n,float amt)
{
acc_no=a;
name=n;
amount=amt;
}
//deposit method
void deposit(float amt)
{
amount=amount+amt;
System.out.println(amt+" deposited");
}
//withdraw method
void withdraw(float amt)
{
if(amount<amt)
{
System.out.println("Insufficient Balance");
}
Else
{
amount=amount-amt;
System.out.println(amt+" withdrawn");
}
}
//method to check the balance of the account
void checkBalance(){System.out.println("Balance is: "+amount);}
//method to display the values of an object
void display(){System.out.println(acc_no+" "+name+" "+amount);}
}
//Creating a test class to deposit and withdraw amount
class TestAccount{
public static void main(String[] args)
{
Account a1=new Account();
a1.insert(832345,"Ankit",1000);
a1.display();
a1.checkBalance();
a1.deposit(40000);
a1.checkBalance();
a1.withdraw(15000);
a1.checkBalance();
}}
Constructors
In Java, a constructor is a block of codes similar to the method.
It is called when an instance of the class is created.
At the time of calling constructor, memory for the object is allocated in the memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is
called.
It calls a default constructor if there is no constructor available in the class.
Java compiler provides a default constructor by default.
Note:
• It is called constructor because it constructs the values at the time of object
creation.
• It is not necessary to write a constructor for a class.
• It is because java compiler creates a default constructor
Example1, we are going to copy the values of one object into another using Java
constructor.
//Java program to initialize the values from one object to another object.
class Student6{
int id;
String name;
//constructor to initialize integer and string
Student6(int i,String n){
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}
Output:
111 Karan
111 Karan
class Student7{
int id;
String name;
Student7(int i,String n)
{
id = i;
name = n;
}
Student7(){}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student7 s1 = new Student7(111,"Karan");
Student7 s2 = new Student7();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}
}
Output:
111 Karan
111 Karan
Output:
111 Karan ITS
222 Aryan ITS
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();
}}
Output:
111 ankit 5000.0
112 sumit 6000.0
If local variables(formal arguments) and instance variables are different, there is no need to use
this keyword like in the following program:
class A
{ void m(){System.out.println("hello m");}
void n()
{ System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}
Output:
hello n
hello m
Output:
hello a
10
Output:
111 ankit java 0.0
112 sumit java 6000.0
Output:
method is invoked
Output:10
Example of this keyword that you return as a statement from the method
class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello java");}
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
Output:
Hello java
In this program, we are printing the reference variable and this, output of both variables
are same.
this keyword refers to the current class instance variable.
class A5{
void m(){
System.out.println(this);//prints same reference ID
}
public static void main(String args[]){
A5 obj=new A5();
System.out.println(obj);//prints the reference ID
obj.m();
}
}
Output:
A5@22b3ea59
A5@22b3ea59
class OuterClass {
int x = 10;
class InnerClass {
int y = 5;
}}
public class Main {
public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.y + myOuter.x);
}}
// Outputs 15 (5 + 10)
}}
// Output
5
Inheritance in Java
It is a mechanism in which one object acquires all the properties and
behaviors of a parent object.
It is an important part of OOPs (Object Oriented programming system).
Inheritance in Java is that you can create new classes that are built upon
existing classes.
It inherits from an existing class
can reuse methods and fields of the parent class.
can add new methods and fields in the current class also.
Inheritance represents the IS-A relationship which is also known as
a parent-child relationship.
Explanation:
In this example, Programmer object can access the field of own class as well
as of Employee class i.e. code reusability.
1. single,
2. multilevel
3. and hierarchical.
Dog class inherits the Animal class, so there is the single inheritance.
class Animal
{
void eat()
{System.out.println("eating...");}
}
class Dog extends Animal
{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...
Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Output:
Compile Time Error
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
Java Interface
Another way to achieve abstraction in Java, is with interfaces.
An interface is a completely "abstract class" that is used to group related methods with empty
bodies:
Syntax of interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}
To access the interface methods, the interface must be "implemented" (kinda like inherited) by
another class with the implements keyword (instead of extends). The body of the interface
method is provided by the "implement" class.
// Example1 Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
// Pig "implements" the Animal interface
class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Notes on Interfaces:
Like abstract classes, interfaces cannot be used to create objects
Interface methods do not have a body - the body is provided by the "implement" class
On implementation of an interface, you must override all of its methods
Interface methods are by default abstract and public
Interface attributes are by default public, static and final
An interface cannot contain a constructor (as it cannot be used to create objects)
What is Polymorphism?
The derivation of the word Polymorphism is from two different Greek words- poly and
morphs.
“Poly” means numerous, and “Morphs” means forms.
Polymorphism means innumerable forms.
Polymorphism, is one of the most significant features of Object-Oriented Programming
Types of Polymorphism
You can perform Polymorphism in Java via two different methods:
1. Method Overloading
2. Method Overriding
What is Method Overloading in Java?
Method overloading is the process that can create multiple methods of the same name
in the same class, and all the methods work in different ways.
Method overloading occurs when there is more than one method of the same name in
the class.
Method Overloading is when a class has multiple methods with the same name, but the
number, types, and order of parameters and the return type of the methods are different.
Java allows the user freedom to use the same name for various functions as long as it
can distinguish between them by the type and number of parameters.
class Shapes {
public void area() {
System.out.println("Find area ");
}
public void area(int r) {
System.out.println("Circle area = "+3.14*r*r);
}
class Main {
public static void main(String[] args) {
Shapes myShape = new Shapes(); // Create a Shapes object
myShape.area();
myShape.area(5);
myShape.area(6.0,1.2);
myShape.area(6,2);
}
}
Output:
Find area
Circle area = 78.5
Triangle area=3.60
Rectangle area=12
class Car
{
void run()
{
System.out.println(“ running”);
}
}
class innova extends Car
{
void run();
{
System.out.println(“ running fast at 120km”);
}
public static void main(String args[])
{
Car c = new innova(); //upcasting
c.run();
}
}
The output of the following program will be;
Running fast at 120 km.
Recursion in Java
Recursion in java is a process in which a method calls itself continuously. A method in
java that calls itself is called recursive method.
Syntax:
returntype methodname(){
//code to be executed
methodname();//calling same method
}
Example:
Output:
Factorial of 5 is: 120