Chapter 3php
Chapter 3php
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, { }.
//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”.
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
// 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());
}
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
There can be a lot of usage of java this keyword. In java, this is a reference
variable that refers to the current object.
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){
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.
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:
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.
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
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
class Student8{
int rollno;
String name;
static String college ="ITS";
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);
}
}
}
Output:1
1
1
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[]){
}
}
Output:1
2
3
class Student9{
int rollno;
String name;
static String college = "ITS";
s1.display();
s2.display();
s3.display();
}
}
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
class Calculate{
static int cube(int x){
return x*x*x;
}
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.
In Java, Method Overloading is not possible by changing the return type of the
method only.
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
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:
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.
}
}
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.
If you make any variable as final, you cannot change the value of final variable(It
will be constant).
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
3.2 Constructors:
Java Constructors
Every time an object is created using the new() keyword, at least one constructor is
called.
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.
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.
In this example, we are creating the no-arg constructor in the Bike class.
It will be invoked at the time of object creation.
Output:
Bike is created
Rule: If there is no constructor in a class, compiler automatically creates a default
constructor.
Output:
0 null
0 null
Java 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.
Output:
111 Karan
222 Aryan
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);}
Output:
111 Karan
111 Karan
In Java, a constructor is just like a method but without return type. It can also be
overloaded like Java methods.
Output:
111 Karan 0
222 Aryan 25
There are many differences between constructors and methods. They are given
below.
A constructor must not have a return A method must have a return type.
type.
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.