JAVA FILE New1
JAVA FILE New1
JAVA FILE New1
Classes and Objects are basic concepts of Object Oriented Programming which revolve
around the real life entities.
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 .
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, { }.
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.
// Class Declaration
public class Dog
{
// Instance Variables
String name;
String breed;
int age;
String 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());
}
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.esuper();), or the Object class constructor if
the class has no other parent (as Object class is parent of all classes either directly or
indirectly).
Using clone() method: clone() method is present in Object class. It creates and returns a
copy of the object.
Anonymous objects
Anonymous objects are the objects that are instantiated but are not stored in a reference
variable.
They are used for immediate method calling.
They will be destroyed after method calling.
They are widely used in different libraries. For example, in AWT libraries, they are
used to perform some action on capturing an event(eg a key press).
In example below, when a key is button(referred by the btn) is pressed, we are simply
creating anonymous object of EventHandler class for just calling handle method.
btn.set
OnAction(new EventHandler()
{
public void handle(ActionEvent event)
{
System.out.println("Hello World!");
}
});
Passing and Returning Objects in Java
Although Java is strictly pass by value, the precise effect differs between whether a primitive
type or a reference type is passed.
When we pass a primitive type to a method, it is passed by value. But when we pass an
object to a method, the situation changes dramatically, because objects are passed by what is
effectively call-by-reference. Java does this interesting thing that’s sort of a hybrid between
pass-by-value and pass-by-reference. Basically, a parameter cannot be changed by the
function, but the function can ask the parameter to change itself via calling some method
within it.
While creating a variable of a class type, we only create a reference to an object. Thus,
when we pass this reference to a method, the parameter that receives it will refer to the
same object as that referred to by the argument.
This effectively means that objects act as if they are passed to methods by use of call-
by-reference.
Changes to the object inside the method do reflect in the object used as an argument.
In Java we can pass objects to methods. For example, consider the following program :
// Java program to demonstrate objects
// passing to methods.
classObjectPassDemo
{
inta, b;
ObjectPassDemo(inti, intj)
{
a = i;
b = j;
}
// return true if o is equal to the invoking
// object notice an object is passed as an
// argument to method
booleanequalTo(ObjectPassDemo o)
{
return(o.a == a &&o.b == b);
}
}
// Driver class
publicclassTest
{
publicstaticvoidmain(String args[])
{
ObjectPassDemo ob1 = newObjectPassDemo(100, 22);
ObjectPassDemo ob2 = newObjectPassDemo(100, 22);
ObjectPassDemo ob3 = newObjectPassDemo(-1, -1);
System.out.println("ob1 == ob2: "+ ob1.equalTo(ob2));
System.out.println("ob1 == ob3: "+ ob1.equalTo(ob3));
}
Output:
ob1 == ob2: true
ob1 == ob3: false
Illustrative images for the above program
From the method side, a reference of type Foo with a name a is declared and it’s
initially assigned to null.
booleanequalTo(ObjectPassDemo o);
As we call the method equalTo, the reference ‘o’ will be assigned to the object which
is passed as an argument, i.e. ‘o’ will refer to ‘ob2’ as following statement execute.
System.out.println("ob1 == ob2: " + ob1.equalTo(ob2));
Now as we can see, equalTo method is called on ‘ob1’ , and ‘o’ is referring to ‘ob2’.
Since values of ‘a’ and ‘b’ are same for both the references, so if(condition) is true, so
boolean true will be return.
if(o.a == a &&o.b == b)
Again ‘o’ will reassign to ‘ob3’ as the following statement execute.
System.out.println("ob1 == ob3: " + ob1.equalTo(ob3));
Now as we can see, equalTo method is called on ‘ob1’ , and ‘o’ is referring to ‘ob3’.
Since values of ‘a’ and ‘b’ are not same for both the references, so if(condition) is false,
so else block will execute and false will be return.
Returning Objects
In java, a method can return any type of data, including objects. For example, in the
following program, the incrByTen( ) method returns an object in which the value of a (an
integer variable) is ten greater than it is in the invoking object
// Java program to demonstrate returning
// of objects
classObjectReturnDemo
{
inta;
ObjectReturnDemo(inti)
{
a = i;
}
// This method returns an object
ObjectReturnDemoincrByTen()
{
ObjectReturnDemo temp =
newObjectReturnDemo(a+10);
returntemp;
}
}
// Driver class
publicclassTest
{
publicstaticvoidmain(String args[])
{
ObjectReturnDemo ob1 = newObjectReturnDemo(2);
ObjectReturnDemo ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: "+ ob1.a);
System.out.println("ob2.a: "+ ob2.a);
}
}
Output:
ob1.a: 2
ob2.a: 12
Note : When an object reference is passed to a method, the reference itself is passed by use
of call-by-value. However, since the value being passed refers to an object, the copy of that
value will still refer to the same object that its corresponding argument does. That’s why we
said that java is strictly pass-by-value.
Inheritance in Java
Inheritance is an important pillar of OOP(Object Oriented Programming). It is the
mechanism in java by which one class is allow to inherit the features(fields and methods) of
another class.
Important terminology:
Super Class: The class whose features are inherited is known as super class(or a base
class or a parent class).
Sub Class: The class that inherits the other class is known as sub class(or a derived
class, extended class, or child class). The subclass can add its own fields and methods in
addition to the superclass fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to
create a new class and there is already a class that includes some of the code that we
want, we can derive our new class from the existing class. By doing this, we are reusing
the fields and methods of the existing class.
class Super{
}
Class Sub extends Super{
}
How to use inheritance in Java
The keyword used for inheritance is extends.
Syntax :
class derived_class extends base-class
{
//methods and fields
}
In practice, inheritance and polymorphism are used together in java to achieve fast
performance and readability of code.
The super keyword
The super keyword is similar to this keyword. Following are the scenarios where the
super keyword is used.
It is used to differentiate the members of superclass from the members of subclass,
if they have same names.
It is used to invoke the superclass constructor from subclass.
Differentiating the Members
If a class is inheriting the properties of another class. And if the members of the superclass
have the names same as the sub class, to differentiate these variables we use super keyword
as shown below.
Super.variable
Super.method();
Types of Inheritance
There are various types of inheritance as demonstrated below.
A very important fact to remember is that Java does not support multiple inheritance. This
means that a class cannot extend more than one class.
However, a class can implement one or more interfaces, which has helped Java get rid of
the impossibility of multiple inheritance.
1. Default: When no access modifier is specified for a class , method or data member – It
is said to be having the default access modifier by default.
The data members, class or methods which are not declared using any access
modifiers i.e. having default access modifier are accessible only within the
same package.
In this example, we will create two packages and the classes in the packages will be having
the default access modifiers and we will try to access a class from one package from a class
of second package.
2. Private: The private access modifier is specified using the keyword private.
The methods or data members declared as private are accessible only within the
class in which they are declared.
Any other class of same package will not be able to access these members.
Top level Classes or interface can not be declared as private because
1. private means “only visible within the enclosing class”.
2. protected means “only visible within the enclosing class and any subclasses”
Hence these modifiers in terms of application to classes, they apply only to nested
classes and not on top level classes.
3.Protected: The protected access modifier is specified using the keyword protected.
The methods or data members declared as protected are accessible within same
package or sub classes in different package.
In this example, we will create two packages p1 and p2. Class A in p1 is made public, to
access it in p2. The method display in class A is protected and class B is inherited from class
A and this protected method is then accessed by creating an object of class B.
4.Public: The public access modifier is specified using the keyword public.
The public access modifier has the widest scope among all other access modifiers.
Classes, methods or data members which are declared as public are accessible from
every where in the program. There is no restriction on the scope of a public data
members.
Important Points:
If other programmers use your class, try to use the most restrictive access level
that makes sense for a particular member. Use private unless you have a good reason
not to.
Avoid public fields except for constants.
1. Use of super with variables: This scenario occurs when a derived class and base class
has same data members. In that case there is a possibility of ambiguity for the JVM. We can
understand it more clearly using this code snippet:
/* Base class vehicle */
class Vehicle
{
int maxSpeed = 120;
}
void display()
{
/* print maxSpeed of base class (vehicle) */
System.out.println("Maximum Speed: " + super.maxSpeed);
}
}
Output:
Maximum speed: 20
In the above example, both base class and subclass have a member maxSpeed. We could
access maxSpeed of base class in subclass using super keyword.
2. Use of super with methods: This is used when we want to call parent class method. So
whenever a parent and child class have same named methods then to resolve ambiguity we
use super keyword. This code snippet helps to understand the said usage of super keyword.
*/Base class Person */
classPerson
{
voidmessage()
{
System.out.println("This is person class");
}
}
/* Subclass Student */
classStudent extendsPerson
{
voidmessage()
{
System.out.println("This is student class");
}
// Note that display() is only in Student class
voiddisplay()
{
// will invoke or call current class message() method
message();
// will invoke or call parent class message() method
super.message();
}
}
/* Driver program to test */
classTest
{
publicstaticvoidmain(String args[])
{
Student s = newStudent();
// calling display() of Student
s.display();
}
}
Output:
This is student class
This is person class
In the above example, we have seen that if we only call method message () then, the current
class message () is invoked but with the use of super keyword, message() of superclass could
also be invoked.
3. Use of super with constructors: super keyword can also be used to access the parent
class constructor. One more important thing is that, ‘’super’ can call both parametric as well
as non parametric constructors depending upon the situation. Following is the code snippet
to explain the above concept:
/* superclass Person */
classPerson
{
Person()
{
System.out.println("Person class Constructor");
}
}
/* subclass Student extending the Person class */
classStudent extendsPerson
{
Student()
{
// invoke or call parent class constructor
super();
System.out.println("Student class Constructor");
}
}
/* Driver program to test*/
classTest
{
publicstaticvoidmain(String[] args)
{
Student s = newStudent();
}
}
Output:
Person class Constructor
Student class Constructor
Final keyword in java
Final keyword is used in different contexts. First of all, final is a non-access
modifier applicable only to a variable, a method or a class. Following are different contexts
where final is used.
Final classes
When a class is declared with final keyword, it is called a final class. A final class cannot be
extended (inherited). There are two uses of a final class:
1. One is definitely to prevent inheritance, as final classes cannot be extended. For
example, all Wrapper Classes like Integer,Float etc. are final classes. We can not extend
them.
2. final class A
3. {
4. // methods and fields
5. }
6. // The following class is illegal.
7. class B extends A
8. {
9. // COMPILE-ERROR! Can't subclass A
10. }
The other use of final with classes is to create an immutable class like the
predefined Stringclass.Youcan not make a class immutable without making it final.
Using final with inheritance :During inheritance, we must declare methods with final
keyword for which we required to follow the same implementation throughout all the
derived classes. Note that it is not necessary to declare final methods in the initial stage of
inheritance(base class always). We can declare final method in any subclass for which we
want that if any other class extends this subclass, then it must follow same implementation of
the method as in the that subclass.