0% found this document useful (0 votes)
17 views

Chapter 3php

The document discusses object-oriented programming concepts including classes, objects, constructors, and access specifiers. A class defines common properties and behaviors for objects through fields and methods. Constructors initialize new objects, while fields represent object state and methods represent behaviors. The this keyword refers to the current object instance.

Uploaded by

Syam Om
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Chapter 3php

The document discusses object-oriented programming concepts including classes, objects, constructors, and access specifiers. A class defines common properties and behaviors for objects through fields and methods. Constructors initialize new objects, while fields represent object state and methods represent behaviors. The this keyword refers to the current object instance.

Uploaded by

Syam Om
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Chapter 3:Object Oriented Programming Concepts

3.1 Class
A class is a user defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one
type. In general, class declarations can include these components, in order:
1. Modifiers : A class can be public or has default access.
2. Class name: The name should begin with a initial letter (capitalized by
convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any,
preceded by the keyword extends. A class can only extend (subclass) one
parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the
class, if any, preceded by the keyword implements. A class can implement
more than one interface.
5. Body: The class body surrounded by braces, { }.

public class Student [extends Person implements Human,LivingBeings]


{

//body of class
}
Constructors are used for initializing new objects. Fields are variables that provides
the state of the class and its objects, and methods are used to implement the
behavior of the class and its objects.
Object
It is a basic unit of Object Oriented Programming and represents the real life
entities. 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 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.
Example of an object : dog
Objects correspond to things found in the real world. For example, a
graphics program may have objects such as “circle”, “square”, “menu”. An online
shopping system might have objects such as “shopping cart”, “customer”, and
“product”.

Declaring Objects (Also called instantiating a class)


When an object of a class is created, the class is said to be instantiated. All the
instances share the attributes and the behavior of the class. But the values of those
attributes, i.e. the state are unique for each object. A single class may have any
number of instances.
Example :

As we declare variables like (type name;). This notifies the compiler that we will
use name to refer to data whose type is type. With a primitive variable, this
declaration also reserves the proper amount of memory for the variable. So for
reference variable, type must be strictly a concrete class name. In
general,we can’t create objects of an abstract class or an interface.
Dog tuffy;
If we declare reference variable(tuffy) like this, its value will be
undetermined(null) until an object is actually created and assigned to it. Simply
declaring a reference variable does not create an object.

Initializing an object
The new operator instantiates a class by allocating memory for a new object and
returning a reference to that memory. The new operator also invokes the
class constructor.
// Class Declaration

public class Dog


{
// Instance Variables
private String name;
private String breed;
private int age;
private String color;

// Constructor Declaration of Class


public Dog(String name, String breed,
int age, String color)
{
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
}

// method 1
public String getName()
{
return name;
}
// method 2
public String getBreed()
{
return breed;
}

// method 3
public int getAge()
{
return age;
}

// method 4
public String getColor()
{
return color;
}

@Override
public String toString()
{
return("Hi my name is "+ this.getName()+
".\nMy breed,age and color are " +
this.getBreed()+"," + this.getAge()+
","+ this.getColor());
}

public static void main(String[] args)


{
Dog tuffy = new Dog("tuffy","papillon", 5, "white");
System.out.println(tuffy.toString());
}
}
Output:
Hi my name is tuffy.
My breed,age and color are papillon,5,white
 This class contains a single constructor. We can recognize a constructor
because its declaration uses the same name as the class and it has no return
type. The Java compiler differentiates the constructors based on the number
and the type of the arguments. The constructor in the Dog class takes four
arguments. The following statement provides “tuffy”,”papillon”,5,”white” as
values for those arguments:
 Dog tuffy = new Dog("tuffy","papillon",5, "white");
 Dog roby = new Dog("roby","German Spheard",10, "black");
Dog
The result of executing this statement can be illustrated as :

Note : All classes have at least one constructor. If a class does not explicitly
declare any, the Java compiler automatically provides a no-argument constructor,
also called the default constructor. This default constructor calls the class parent’s
no-argument constructor (as it contain only one statement i.e super();), or
the Object class constructor if the class has no other parent (as Object class is
parent of all classes either directly or indirectly).
 Access Specifiers

Visibility Public Protected Default Private


From the class YES YES YES YES
From any class in same YES YES YES NO
package
From a subclass in YES YES YES NO
same package
From a subclass YES YES,through NO NO
outside the same inheritance
package
From any non sub class YES NO NO NO
outside the package

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

Understanding the problem without this keyword


Let's understand the problem if we don't use this keyword by the example given below:

class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
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:

0 null 0.0
0 null 0.0

In the above example, parameters (formal arguments) and instance variables are
same. So, we are using this keyword to distinguish local variable and instance
variable.

Solution of the above problem by this keyword


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();
}}

Output:

111 ankit 5000


112 sumit 6000

2) this: to invoke current class method

You may invoke the method of the current class by using the this keyword. If
you don't use the this keyword, compiler automatically adds this keyword while
invoking the method. Let's see the example
class A{
void m(){System.out.println("hello m");}
void n(){
System.out.println("hello n");
//m();//same as this.m()
this.m(); //a.m()
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}

Output:

hello n
hello m
3) this() : to invoke current class constructor:The this() constructor call can be used
to invoke the current class constructor. It is used to reuse the constructor. In other
words, it is used for constructor chaining.

Calling default constructor from parameterized constructor:

class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}

Output:

hello a
10
Calling parameterized constructor from default constructor:

class A{
A(){
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
class TestThis6{
public static void main(String args[]){
A a=new A();
}}

Output:

5
hello a

 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:
variable (also known as class variable)
method (also known as class method)
block
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).
Understanding problem without static variable
class Student{
int rollno;
String name;
String college="ITS";
}
Suppose there are 500 students in my college, now all instance data members
will get memory each time when object is created.All student have its unique
rollno and name so instance data member is good.Here, college refers to the
common property of all objects.If we make it static,this field will get memory
only once.
Java static property is shared to all objects.
Example of static variable
//Program of static variable

class Student8{
int rollno;
String name;
static String college ="ITS";

Student8(int r,String n){


rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){


Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");

s1.display();
s2.display();
}
}
Output:111 Karan ITS
222 Aryan ITS
Program of counter without static variable
In this example, we have created an instance variable named count which is
incremented in the constructor. Since instance variable gets the memory at the
time of object creation, each object will have the copy of the instance variable,
if it is incremented, it won't reflect to other objects. So each objects will have
the value 1 in the count variable.
class Counter{
int count=0;//will get memory when instance is created

Counter(){
count++;
System.out.println(count);
}

public static void main(String args[]){

Counter c1=new Counter();


Counter c2=new Counter();
Counter c3=new Counter();

}
}
Output:1
1
1

Program of counter by static variable


As we have mentioned above, static variable will get the memory only once, if
any object changes the value of the static variable, it will reta

in its value.
class Counter2{
static int count=0;//will get memory only once and retain its value

Counter2(){
count++;
System.out.println(count);
}
public static void main(String args[]){

Counter2 c1=new Counter2();


Counter2 c2=new Counter2();
Counter2 c3=new Counter2();

}
}
Output:1
2
3

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
//Program of changing the common property of all objects(static field).

class Student9{
int rollno;
String name;
static String college = "ITS";

static void change(){


college = "BBDIT";
}

Student9(int r, String n){


rollno = r;
name = n;
}

void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){


Student9.change();
Student9 s1 = new Student9 (111,"Karan");
Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");

s1.display();
s2.display();
s3.display();
}
}
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

Another example of static method that performs normal calculation


//Program to get cube of a given number by static method

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);
}
}
Output:125
Restrictions for static method
There are two main restrictions for the static method. They are:
The static method can not use non static data member or call non-static method
directly.
this and super cannot be used in static context.
class A{
int a=40;//non static

public static void main(String args[]){


System.out.println(a);
}
}
Output:Compile Time Error

Method Overloading in Java

If a class has multiple methods having same name but different in 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 behavior 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.

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

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.

class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}

Output:

22
33

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.

class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}

Output:

22
24.9
Q) Why Method Overloading is not possible by changing the return type of method
only?

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

class Adder{
static int add(int a,int b){return a+b;}
static double add(int a,int b){return a+b;}
}
class TestOverloading3{
public static void main(String[] args){
System.out.println(Adder.add(11,11));//ambiguity
}}

Output:

Compile Time Error: method add(int,int) is already defined in class Adder

System.out.println(Adder.add(11,11)); //Here, how can java determine which


sum() method should be called?

Note: Compile Time Error is better than Run Time Error. So, java compiler
renders compiler time error if you declare the same method having same
parameters.

Method Overloading and Type Promotion

One type is promoted to another implicitly if no matching datatype is found. Let's


understand the concept by the figure given below:
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


class OverloadingCalculation1{
void sum(int a,long b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}

public static void main(String args[]){


OverloadingCalculation1 obj=new OverloadingCalculation1();
obj.sum(20,20);//now second int literal will be promoted to long
obj.sum(20,20,20);

}
}
Output:40
60
Final Keyword In Java

The final keyword in java is used to restrict the user. The java final keyword can
be used in many context. Final can be:

1. variable
2. method
3. class

The final keyword can be applied with the variables, a final variable that have no
value it is called blank final variable or uninitialized final variable. It can be
initialized in the constructor only. The blank final variable can be static also which
will be initialized in the static block only. We will have detailed learning of these.
Let's first learn the basics of final keyword.

1) Java final variable

If you make any variable as final, you cannot change the value of final variable(It
will be constant).

Example of final variable

There is a final variable speedlimit, we are going to change the value of this
variable, but It can't be changed because final variable once assigned a value can
never be changed.

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

2) Java final method

If you make any method as final, you cannot override it.


Example of final method
class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}
Output:Compile Time Error

3) Java final class

If you make any class as final, you cannot extend it.

Example of final class


final class Bike{}

class Honda1 extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}
Output:Compile Time Error

3.2 Constructors:

Java 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. In such


case, Java compiler provides a default constructor by default.

There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.

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 if your class doesn't have any.

Rules for creating Java constructor

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

Note: We can use access modifiers while declaring a constructor. It controls the
object creation. In other words, we can have private, protected, public or default
constructor in Java.

Types of Java constructors

There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor

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

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.

//Java Program to create and call a default constructor


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();
}
}

Output:

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

Example of default constructor that displays the default values


//Let us see another example of default constructor
//which displays the default values
class Student3{
int id;
String name;
//method to display the value of id and name
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3();
//displaying values of the object
s1.display();
s2.display();
}
}

Output:

0 null
0 null
Java Parameterized Constructor

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


constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct


objects. However, you can provide the same values also.

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.

//Java Program to demonstrate the use of the 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();
}
}

Output:

111 Karan
222 Aryan

Java Copy Constructor

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

In this example, 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

Constructor Overloading in Java

In Java, a constructor is just like a method but without return type. It can also be
overloaded like Java methods.

Constructor overloading in Java is a technique of having more than one constructor


with different parameter lists. They are arranged in a way that each constructor
performs a different task. They are differentiated by the compiler by the number of
parameters in the list and their types.

Example of Constructor Overloading


//Java program to overload constructors
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}

Output:

111 Karan 0
222 Aryan 25

Difference between constructor and method in Java

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

Java Constructor Java Method

A constructor is used to initialize the A method is used to expose the behavior


state of an object. of an object.

A constructor must not have a return A method must have a return type.
type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default The method is not provided by the
constructor if you don't have any compiler in any case.
constructor in a class.

The constructor name must be same as The method name may or may not be
the class name. same as the class name.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy