0% found this document useful (0 votes)
2 views31 pages

Unit-2_Java

Unit 2 covers the concepts of classes and objects in Java, explaining the structure of a class, access modifiers, and the creation of objects. It discusses constructors, encapsulation, inheritance, and polymorphism, detailing method overloading and overriding as key features of object-oriented programming. The unit emphasizes the importance of encapsulation for data control and the dynamic nature of polymorphism in Java.

Uploaded by

salonisingh58494
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)
2 views31 pages

Unit-2_Java

Unit 2 covers the concepts of classes and objects in Java, explaining the structure of a class, access modifiers, and the creation of objects. It discusses constructors, encapsulation, inheritance, and polymorphism, detailing method overloading and overriding as key features of object-oriented programming. The unit emphasizes the importance of encapsulation for data control and the dynamic nature of polymorphism in Java.

Uploaded by

salonisingh58494
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/ 31

Unit 2.

Classes and Objects

2.1 Simple Class, Field


A class in Java is a set of objects which shares common characteristics/
behavior and common properties/ attributes. It is a user-defined blueprint or
prototype from which objects are created. For example, Student is a class while
a particular student named Ravi is an object.
Properties of Java Classes
1. Class is not a real-world entity. It is just a template or blueprint or
prototype from which objects are created.
2. Class does not occupy memory.
3. Class is a group of variables of different data types and a group of
methods.
4. A Class in Java can contain:
• Data member
• Method
• Constructor
• Nested Class
• Interface
Class Declaration in Java
access_modifier class <class_name>
{
data member;
method;
constructor;
nested class;
interface;
}
class Student {
// data member (also instance variable)
int id;
// data member (also instance variable)
String name;

public static void main(String args[])


{
// creating an object of
// Student
Student s1 = new Student();
Unit 2. Classes and Objects
System.out.println(s1.id);
System.out.println(s1.name);
}
}

2.2 Access Controls, Object creation


Access Controls

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
2. Default: The access level of a default modifier is only within the package.
It cannot be accessed from outside the package. If you do not specify any
access level, it will be the default.

If you don't use any modifier, it is treated as default by default. The


default modifier is accessible only within package. It cannot be accessed
from outside the package. It provides more accessibility than private. But,
it is more restrictive than protected, and public.

3. Protected: The access level of a protected modifier is within the package


and outside the package through child class. If you do not make the child
class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the package and
outside the package.
Access
within
within
outside package by
outside
Modifier
class
package
subclass only
package
Private Y N N N

Default Y Y N N

Unit 2. Classes and Objects


Protected Y Y Y N

Public Y Y Y Y

Java Objects
An object in Java is a basic unit of Object-Oriented Programming and
represents real-life entities. Objects are the instances of a class that are created
to use the attributes and methods of a class. A typical Java program creates
many objects, which as you know, interact by invoking methods. An object
consists of :
1. State: It is represented by attributes of an object. It also reflects the
properties of an object.
2. Behavior: It is represented by the methods of an object. It also reflects
the response of an object with other objects.
3. Identity: It gives a unique name to an object and enables one object
to interact with other objects.

Ways to Create an Object of a Class


1. Using new keyword
It is the most common and general way to create an object in Java.
Example:
// creating object of class Test
Test t = new Test();

2. Using Class.forName(String className) method

There is a pre-defined class in java.lang package with name Class. The


forName(String className) method returns the Class object associated with
the class with the given string name. We have to give a fully qualified name for
a class. On calling the new Instance() method on this Class object returns a new
instance of the class with the given string name.
Example:
Test obj = (Test)Class.forName("com.p1.Test").newInstance();

3. Using clone() method


clone() method is present in the Object class. It creates and returns a copy of
the object.
Example:
Unit 2. Classes and Objects

// creating object of class Test


Test t1 = new Test();
// creating clone of above object
Test t2 = (Test)t1.clone();

4. Deserialization
De-serialization is a technique of reading an object from the saved state in a
file. Refer to Serialization/De-Serialization in Java
Example:
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
Object obj = in.readObject();

2.3 Construction and Initialization

• 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.
In such case, Java compiler provides a default constructor by default.

There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized
Types of Java constructors
1. Default constructor (no-arg constructor)

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


parameter.

Syntax: <class_name>(){}
Example:
Unit 2. Classes and Objects
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}

2. Parameterized constructor

A constructor which has a specific number of parameters is called a


parameterized constructor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}

Unit 2. Classes and Objects

There is no copy constructor in Java. However, we can copy the values from one
object to another like copy constructor in C++.

2.4 Inheritance and Polymorphism in Java


Data encapsulation
Encapsulation in Java is a process of wrapping code and data together into a
single unit, for example, a capsule which is mixed of several medicines.

Advantage of Encapsulation in Java

• By providing only a setter or getter method, you can make the class read
only or write-only. In other words, you can skip the getter or setter
methods.
• It provides you the control over the data. Suppose you want to set the
value of id which should be greater than 100 only, you can write the logic
inside the setter method. You can write the logic not to store the negative
numbers in the setter methods.
• It is a way to achieve data hiding in Java because other class will not be
able to access the data through the private data members.
• The encapsulate class is easy to test. So, it is better for unit testing.
//A Account class which is a fully encapsulated class.
//It has a private data member and getter and setter
methods. class Account {
//private data members
private long acc_no;
private String name,email;
private float amount;
//public getter and setter methods
public long getAcc_no() {
return acc_no;
}

Unit 2. Classes and Objects


public void setAcc_no(long acc_no) {
this.acc_no = acc_no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public float getAmount() {
return amount;
}
public void setAmount(float amount) {
this.amount = amount;
}}

//A Java class to test the encapsulated class Account.


public class TestEncapsulation {
public static void main(String[] args) {
//creating instance of Account class
Account acc=new Account();
//setting values through setter methods
acc.setAcc_no(7560504000L);
acc.setName("Sonoo Jaiswal");
acc.setEmail("[email protected]");
acc.setAmount(500000f);
//getting values through getter methods
System.out.println(acc.getAcc_no()+" "+acc.getName()+"
"+acc.g etEmail()+" "+acc.getAmount());
}
Unit 2. Classes and Objects
}

Polymorphism: overriding and overloading methods


The derivation of the word Polymorphism is from two different Greek words
poly and morphs. “Poly” means numerous, and “Morphs” means forms. So,
polymorphism means innumerable forms. Polymorphism, therefore, is one of
the most significant features of Object-Oriented Programming.
Real-Life Examples of Polymorphism

An individual can have different relationships with different people. A woman


can be a mother, a daughter, a sister, and a friend, all at the same time, i.e. she
performs other behaviors in different situations.

The human body has different organs. Every organ has a different function to
perform; the heart is responsible for blood flow, the lungs for breathing, the
brain for cognitive activity, and the kidneys for excretion. So we have a
standard method function that performs differently depending upon the organ
of the body.

Polymorphism in Java Example

A superclass named “Shapes” has a method called “area()”. Subclasses of


“Shapes” can be “Triangle”, “circle”, “Rectangle”, etc. Each subclass has its way
of calculating area. Using Inheritance and Polymorphism means, the subclasses
can use the “area()” method to find the area’s formula for that shape.
class Shapes {

public void area() {

System.out.println("The formula for area of ");

}
Unit 2. Classes and Objects

class Triangle extends Shapes {

public void area() {

System.out.println("Triangle is ½ * base * height ");

class Circle extends Shapes {

public void area() {

System.out.println("Circle is 3.14 * radius * radius ");

class Main {

public static void main(String[] args) {

Shapes myShape = new Shapes(); // Create a Shapes object

Shapes myTriangle = new Triangle(); // Create a Triangle object

Shapes myCircle = new Circle(); // Create a Circle object

myShape.area();

myTriangle.area();
myShape.area();
Unit 2. Classes and Objects

myCircle.area();

Output:

The formula for the area of the Triangle is ½ * base * height The formula for
the area of the Circle is 3.14 * radius * radius

class Shape {

public void draw() {

System.out.println("Drawing a shape");

class Circle extends Shape {

@Override

public void draw() {

System.out.println("Drawing a circle");

}
Unit 2. Classes and Objects
class Square extends Shape {

@Override

public void draw() {

System.out.println("Drawing a square");

class Main {

public static void main(String[] args) {

Shape s1 = new Circle();

Shape s2 = new Square();

s1.draw(); // Output: "Drawing a circle"

s2.draw(); // Output: "Drawing a square"

In this example, we have a base class Shape with a single method draw() that
prints “Drawing a shape” to the console. We then create two subclasses, Circle
and Square, that override the draw() method to print “Drawing a circle” and
“Drawing a square” respectively.

In the main method, we create two instances of the Shape class, s1 and s2,
which are actually instances of the Circle and Square subclasses. When we call
the draw() method on these objects, the correct implementation is called
Unit 2. Classes and Objects

based on the actual type of the object, this is run-time polymorphism. The
program will output: “Drawing a circle” and “Drawing a square”

In this example, the draw() method is overridden in the subclasses, and this
allows for the program to determine which method to use at runtime. This is
known as runtime polymorphism or dynamic polymorphism, Because at
runtime the JVM determines the actual type of the object and calls the
corresponding method.

Types of Polymorphism

You can perform Polymorphism in Java via two different methods:

1. Method Overloading
2. Method Overriding
3.
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.
class Shapes {

public void area() {

System.out.println("Find area ");

public void area(int r) {

System.out.println("Circle area = "+3.14*r*r);

}
Unit 2. Classes and Objects

public void area(double b, double h) {

System.out.println("Triangle area="+0.5*b*h);

public void area(int l, int b) {

System.out.println("Rectangle area="+l*b);

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);
Unit 2. Classes and Objects
}

Output:

Find area Circle area = 78.5 Triangle area=3.60 Rectangle area=12

What is Method Overriding in Java?

Method overriding is the process when the subclass or a child class has the
same method as declared in the parent class.
class Vehicle{

//defining a method

void run(){System.out.println("Vehicle is moving");}

//Creating a child class

class Car2 extends Vehicle{

//defining the same method as in the parent class

void run(){System.out.println("car is running safely");}

public static void main(String args[]){

Unit 2. Classes and Objects


Car2 obj = new Car2();//creating object

obj.run();//calling method

Output:

Car is running safely

Also, Polymorphism in Java can be classified into two types, i.e:

1. Static/Compile-Time Polymorphism
2. Dynamic/Runtime Polymorphism

What is Compile-Time Polymorphism in Java?

Compile Time Polymorphism In Java is also known as Static Polymorphism.


Furthermore, the call to the method is resolved at compile time. Compile-Time
polymorphism is achieved through Method Overloading. This type of
polymorphism can also be achieved through Operator Overloading. However,
Java does not support Operator Overloading.

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. Check out some of the important questions on run
time polymorphism in java interview questions.

What is Runtime Polymorphism in Java?

Runtime polymorphism in Java is also popularly known as Dynamic Binding or


Dynamic Method Dispatch. In this process, the call to an overridden method
Unit 2. Classes and Objects

is resolved dynamically at runtime rather than at compile-time. You can achieve


Runtime polymorphism via Method Overriding.

Method Overriding is done when a child or a subclass has a method with the
same name, parameters, and return type as the parent or the superclass; then
that function overrides the function in the superclass. In simpler terms, if the
subclass provides its definition to a method already present in the superclass;
then that function in the base class is said to be overridden.

Also, it should be noted that runtime polymorphism can only be achieved


through functions and not data members.

Overriding is done by using a reference variable of the superclass. The method


to be called is determined based on the object which is being referred to by the
reference variable. This is also known as Upcasting.

Upcasting takes place when the Parent class’s reference variable refers to the
object of the child class. For example:
class A{}

class B extends A{}

A a=new B(); //upcasting

Examples of Runtime Polymorphism in Java

Example 1:

In this example, we are creating one superclass Animal and three subclasses,
Herbivores, Carnivores, and Omnivores. Subclasses extend the superclass and
override its eat() method. We will call the eat() method by the reference
variable of Parent class, i.e. Animal class. As it refers to the base class object
and the base class method overrides the superclass method; the base class
method is invoked at runtime. As Java Virtual Machine or the JVM and not the
compiler determines method invocation, it is, therefore, runtime
polymorphism.
Unit 2. Classes and Objects

class Animal{
void eat(){

System.out.println("Animals Eat");

class herbivores extends Animal{

void eat(){

System.out.println("Herbivores Eat Plants");

class omnivores extends Animal{

void eat(){

System.out.println("Omnivores Eat Plants and meat");

class carnivores extends Animal{

void eat(){

System.out.println("Carnivores Eat meat");

}
Unit 2. Classes and Objects
}

class main{

public static void main(String args[]){

Animal A = new Animal();

Animal h = new herbivores(); //upcasting

Animal o = new omnivores(); //upcasting

Animal c = new carnivores(); //upcasting

A.eat();

h.eat();

o.eat();

c.eat();

Output:

Animals eat Herbivores Eat Plants Omnivores Eat Plants and meat
Carnivores eat meat

Advantages of Polymorphism in Java


Unit 2. Classes and Objects
1. It provides reusability to the code. The classes that are written,
tested and implemented can be reused multiple times.
Furthermore, it saves a lot of time for the coder. Also, the one can
change the code without affecting the original code.
2. A single variable can be used to store multiple data values. The
value of a variable you inherit from the superclass into the
subclass can be changed without changing that variable’s value in
the superclass; or any other subclasses.
3. With lesser lines of code, it becomes easier for the programmer to
debug the code.

Problems with Polymorphism

Polymorphism is quite challenging while implementation.

• It tends to reduce the readability of the code.


• It raises some serious performance issues in real-time as well.

Inheritance

Inheritance in Java 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).

The idea behind inheritance in Java is that you can create new classes that are
built upon existing classes. When you inherit from an existing class, you can
reuse methods and fields of the parent class. Moreover, you can add new
methods and fields in your current class also.

class Subclass-name extends Superclass-name


{
//methods and fields
}
class Employee{
float salary=40000;
}
Unit 2. Classes and Objects
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}

Types of inheritance in java

Unit 2. Classes and Objects


Multiple inheritance is not supported in java.

2.5 this and super keywords


this keyword

The this keyword refers to the current object in a method or constructor.

The most common use of this keyword is to eliminate the confusion between
class attributes and parameters with the same name (because a class attribute
is shadowed by a method or constructor parameter).

this can also be used to:

• Invoke current class constructor


• Invoke current class method
• Return the current class object
• Pass an argument in the method call
• Pass an argument in the constructor call

public class Main {


int x;

Unit 2. Classes and Objects


// Constructor with a parameter
public Main(int x) {
this.x = x;
}

// Call the constructor


public static void main(String[] args) {
Main myObj = new Main(5);
System.out.println("Value of x = " + myObj.x);
}
}

super keyword
• 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
o super can be used to refer immediate parent class instance variable.
o super can be used to invoke immediate parent class method. o
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.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal
class }
}
class TestSuper1{
Unit 2. Classes and Objects
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}

2) super can be used to invoke parent class method


class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}

3) super is used to invoke parent class constructor.


class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{

Unit 2. Classes and Objects


public static void main(String args[]){
Dog d=new Dog();
}}

2.6 Static members, static block, static class


Static members
o 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.
o Advantages of static variable: It makes your program memory efficient
(i.e., it saves memory).
//Java Program to demonstrate the use of static
variable class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
void display (){System.out.println(rollno+" "+name+" "+coll
ege);}
}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line
of code
//Student.college="BBDIT";

Unit 2. Classes and Objects


s1.display();
s2.display();
}
}

static block

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

o A static method belongs to the class rather than the object of a class. o A
static method can be invoked without the need for creating an instance of a
class.
o A static method can access static data member and can change the value
of it.
class Calculate{
static int cube(int x){
return x*x*x;
}

public static void main(String args[]){


int result=Calculate.cube(5);
System.out.println(result);
}
}

static class
A class can be declared static only if it is a nested class. It does not require any
reference of the outer class. The property of the static class is that it does not
allows us to access the non-static members of the outer class.
public class JavaStaticClassExample
{
private static String s= "Javatpoint";

Unit 2. Classes and Objects


//Static and nested class
static class StaticNestedClass
{
//non-static method of the nested class
public void show()
{
//prints the string defined in base class
System.out.println(s);
}
}
public static void main(String args[])
{
JavaStaticClassExample.StaticNestedClass obj = new
JavaStaticClass Example.StaticNestedClass();
//invoking the method of the nested class
obj.show();
}
}

2.7 Interfaces:
What is an Interface?
An interface is just like Java Class, but it only has static constants and abstract
method. Java uses Interface to implement multiple inheritance. A Java class
can implement multiple Java Interfaces. All methods in an interface are
implicitly public and abstract.
Syntax for Declaring Interface
interface {
//methods
}
To use an interface in your class, append the keyword "implements" after your
class name followed by the interface name.
class Dog implements Pet
Unit 2. Classes and Objects
interface RidableAnimal extends Animal, Vehicle

Why is an Interface required?


To understand the concept of Java Interface better, let see an example. The
class "Media Player" has two subclasses: CD player and DVD player. Each
having its unique implementation method to play music.Another class "Combo
drive" is inheriting both CD and DVD (see image below). Which play method
should it inherit? This may cause serious design issues. And hence, Java does
not allow multiple inheritance.
Now let's take another example of Dog.
Suppose you have a requirement where class "dog" inheriting class "animal"
and "Pet" (see image below). But you cannot extend two classes in Java. So
what would you do? The solution is Interface.
The rulebook for interface says,
o An interface is 100% abstract class and has only abstract methods.
o Class can implement any number of interfaces.
o Class Dog can extend to class "Animal" and implement interface as
"Pet".
Java Interface Example:
Step 1) Copy following code into an editor.
interface Pet{
public void test();
}
class Dog implements Pet{
public void test(){
System.out.println("Interface Method Implemented");
}
public static void main(String args[]){
Pet p = new Dog();
Unit 2. Classes and Objects

p.test();
}
}
Step 2) Save , Compile & Run the code. Observe the Output.
Difference between Class and Interface

When to use Interface and Abstract Class?


• Use an abstract class when a template needs to be defined for a group
of subclasses
• Use an interface when a role needs to be defined for other classes,
regardless of the inheritance tree of these classes
Must know facts about Interface
• A Java class can implement multiple Java Interfaces. It is necessary that
the class must implement all the methods declared in the interfaces. • Class
should override all the abstract methods declared in the interface • The
interface allows sending a message to an object without concerning which
classes it belongs.
• Class needs to provide functionality for the methods declared in the
interface.
• All methods in an interface are implicitly public and abstract •
An interface cannot be instantiated
• An interface reference can point to objects of its implementing classes •
An interface can extend from one or many interfaces. Class can extend
only one class but implement any number of interfaces
Unit 2. Classes and Objects

• An interface cannot implement another Interface. It has to extend


another interface if needed.
• An interface which is declared inside another interface is referred as
nested interface
• At the time of declaration, interface variable must be initialized.
Otherwise, the compiler will throw an error.
• The class cannot implement two interfaces in java that have methods
with same name but different return type.

You might also like