Object and Classes
Since Java is an object oriented language, complete java language is build on classes and object.
Java is also known as a strong Object oriented programming language(oops).
OOPS is a programming approach which provides solution to problems with the help of
algorithms based on real world, It uses real world approach to solve a problem, So object
oriented technique offers better and easy way to write program then procedural programming
model such as C, ALGOL, PASCAL.
Main Features of OOPS
+ Inheritence
+ Polymorphism
+ Encapsulation
+ Abstraction
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as,
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
When one task is performed by different ways i.e, known as polymorphism. For example:
to convense the customer differently, to draw something e.g. shape or rectangle ete.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.
In java, we use method overloading and method overriding to achieve polymorphism,
Abstraction
Hiding intemal details and showing functionality is known as abstraction. For example:
phone call, we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction
As an object oriented language Java supports all the features given above.
Class
In Java everything is encapsulated under classes. Class is the core of Java language. Class can be
defined as a template/ blueprint that describe the behaviors /states of a particular entity. A class
defines new data type. Once defined this new type can be used to create object of that type.
Object is an instance of class. You may also call it as physical existence of a logical template
class.A class is declared using elass keyword. A class contain both data and code that operate on that
data, The data or variables defined within a elass are called instance variables and the code that
operates on this data is known as methods.
Rules for Java Class
+ Aclass can have only public or default(no modifier) access specifier.
+ Itcan be either abstract, final or concrete (normal class).
+ Itmust have the class keyword, and class must be followed by a legal identifier.
«It may optionally extend one parent class. By default, it will extend java.lang.Object.
+ Itmay optionally implement any number of comma-separated interfaces,
+ The class's variables and methods are declared within a set of curly braces (3.
+ Bach java source file may contain only one public class. A source file may contain any
number of default visible classes.
+ Finally, the source file name must match the public class name and it must have a java
suffix.
A simple class example
Suppose, Student is a elass and student's name, roll number, age will be its property. Lets see this
in Java syntax
class
rolino;
When a reference is made to a particular student with its property then it becomes an object,
physical existence of Student class.
udent std-new Student ();
After the above statement std is instance/object of Student class. Here the new keyword creates
an actual physical copy of the object and assign it to the std variable. It will have physical
existence and get memory in heap area. The new operator dynamically allocates memory for
an objectMethods in Java
Method describe behavior of an object. A method is a collection of statements that are group
together to perform an operation.
Syntax:
return-type methodName (parameter-list)
{Pood of method
Example of a Method
public ame (String st)
String name="Spack";
public String getName(string st)
Modifier : Modifier are access type of method. We will discuss it in detail later.Return Type :
method heading
method may return value. Data type of value return by a method is declare in
‘Method name : Actual name of the method.
Parameter : Value passed to a method
Method body : collection of statement that defines what method does.
Parameter Vs. Argument
While talking about method, it is important to know the difference between two terms
parameter and argument.
Parameter is variable defined by a method that receives value when the method is called.
Parameter are always local to the method they dont have scope outside the method. While
argument is a value that is passed to a method when it is called.
public void sum( int x; int y >
System.out.printing * string names
}
Class child extends Parent [
_ string name;
voia detail 0
Example of Child class refering Parent class property using super keyword
class Parent
(
String name;
:
public class Child extends Parent (
String name;
public void details()
(
super-name = "Parent"; //refers to parent class member
name = "Child";
System.out.print1n(super.name+" and "+name) +
,
public static void main(String] args)
child cobj = new child();
cobj.details()Output
Parent and Child
Example of Child class refering Parent class methods using super keyword
class Parent
ring name;
public void details ()
name = "Parent";
System, out.println (name) 7
class Child extends Parent
public void details ()
super details (); //ealling Parent class details() method
System. out .printin (name);
public
void main(Striag{] azgs)
child cobj = new child();
cobj.details(;
Output
chil
Example of Child class calling Parent class constructor using super keyword
class Parent
String name;
public Parent (String n)
public class Child extends Parent
ring name;
public Child(
ring nl, String n2)
super (nl) //passing argument to parent class constructor
this.name = n2;D
public void details()
‘
System.out printin(super.name!" and "Iname);
)
public static void main(String{] args)
‘
child cobj = new Chila("Barent", "child") ;
cobj .details();
,
Output
Parent and ChildAggregation (HAS-A)
HAS-A relationship is based on usage, rather than inheritance. In other words, class A has-a
relationship with class B, if code in class A has a reference to an instance of class B.
Example
class Student
(
String name;
Address ad;
,
Here you can say that Student has-aAddress.
Student class has an instance variable of type Address. Student code can use Address reference
to invoke methods on the Address, and get Address behavior.
Aggregation allow you to design classes that follow good Object Oriented practices. It also
provide code reusability.
Example of Aggregation
class Author
(
String authorName,
int age;
String place;
Author (String name, int age,String place)
{
this. authorName=name;
this.age-ages
this.place=place;
}
public String getActhorName ()
4
return authorName;
}
public int getage()
4
retuzn age;)
public String getPlace()
{
return place;
)
'
class Book
(
String name;
int price;
Author auth;
Book (String n, int p,Author at}
‘
this.nane=n;
this.pric
this.aut
)
public void showDetail()
{
system.out.print1n("Book is"+name) +
System.out.printin("price “+price);
System. out.println("Author is "#auth.getAuthorName());
)
,
ti
class Test
(
publ
{
Author atl
Book b=new Book
b,showDetail ();
}
:
Output:
Book is Java.
price is 550.
Ruther is me
static void main(String args{])
jew Author ("Me", 22, "Tndia")
"Java", 550, ath);
Composition in java:
‘Composition is restricted form of Aggregation, For example a class Car cannot exist without
Engine.
class Car
private Engine engines
Car (Engine en)
{
engine = ent
J
»Q. When to use Inheritance and Aggregation?
When you need (o use property and behaviour of a class without modifying it inside your class.
In such case Aggregation is a better option. Whereas when you need to use and modify property
and behaviour of a class inside your class, its best to use Inheritance.Method Overriding
When a method in a sub class has same name and type signature as a method in its super class,
then the method is known as overridden method. Method overriding is also referred to as runtime
polymorphism. The key benefit of overriding is the abitility to define method that's specific to
a particular subclass type.
Example of Method Overriding
class Animal
public void eat()
{
Systen.ovt printin ("Generic Animal eating");
)
extends Anima
ublic void eat() //eat() method overriden by Dog class.
{
m.out.printin ("Dog eat mea
)
‘As you can see here Dog class gives it own implementation of eat() method. Method must have same
name and same type signature.
NOTE : Static methods cannot be overridden because, a static method is bounded with class
where as instance method is bounded with object.
Difference between Overloading and Overriding
Method Overloading Method Overriding
Parameter must be different and
Both name and parameter must be same.
name must be same.
Compile time polymorphism. Runtime polymorphism.
Increase readability of code Increase reusability of code.
Access specifier most not be more restrictive than original
Access specifier can be changed.
Cees SPocNer CaN Ne
)
Inner ii
in.show()7
,
)
,
ji<3;i++)
de inner "+(count++));
jew Taner (5
class Test
(
public static void main(String|] args)
{
outer otsnew Outer ();ot.display();
)
b
output:
Inside inner
Inside inner
Inside inne
Inside inner
Inside inner
Example of Inner class instantiated outside Outer class
class Outer
(
int counts
public void display()
4
Inner in=new Inner ();
in.show ()
)
class Inner
‘
public void show()
System.out.println("Inside inner "+(++count))s
,
)
,
class Test
qi
public static void main(string{] args)
1
Outer ot-new outer ();
Outer.Inner in= ot.new Inner();
in.show()
)
»
output
Inside inner 1
Annonymous class
A class without any name is called Annonymous class.
interface Animal
(
void typed;
,
public class atest {
public static void main(String args{))‘
Animal an = new Animal ()(
public void type(}
system. ou
n("Annonymous animal");
M
an.type 0;
)
output
jonymous animal
//Renonymous cla:
Here a class is created which implements Animal interace and its name will be decided by the
compiler. This anonymous class will provide implementation of type() method