Object Orientation in Java
Object Orientation in Java
Object Orientation in Java
A bulb:
3. It has real features like the glass covering, filament and holder. Member Variables
5. A bulb manufacturing factory produces many bulbs based on a basic description / pattern of
what a bulb is. Class
Class
A class is a group of objects that has common properties.
A class is a construct created in object-oriented programming languages that enables creation of objects.
Also sometimes called blueprint or template or prototype from which objects are created.
A class is an abstraction.
Variable
declarations
Methods
definitions
class Student
{ {
int rollno;
String name;
Student stud1;
Employee emp1;
• The new operator is used to create an object of that reference type
E.g
class Student
{
int rollno;
String name;
Memory Allocations:
When a Java virtual machine runs a program, it needs memory to store many things, including byte codes
and other information it extracts from loaded class files, objects the program instantiates, parameters to
methods, return values, local variables, and intermediate results of computations. The Java virtual
machine organizes the memory it needs to execute a program into several runtime data areas.
Constructor in java is a special type of method that is used to initialize the object.
– A constructor can be defined with any access specifier (like private, public)
– There can be more than one constructor for a class. (constructor overloading)
– Space is allocated for an object only when the constructor is called. Declaring a variable
of class and not calling new does not consume any memory!
Type of Constructors:
Default Constructor:
class Sample
id = 101;
Rule: Rule: If there is no constructor in a class, compiler automatically creates a default constructor.
class Student
{
int id;
String name;
Student4(int i,String n)
{
id = i;
name = n;
10. }
11. void display()
12. {
13. System.out.println(id+" "+name);
14. }
15.
16. public static void main(String args[])
17. {
18. Student4 s1 = new Student4(111,"Raj”);
19. Student4 s2 = new Student4(222,”Sam");
20. s1.display();
21. s2.display();
22. }
23. }
Constructor Overloading
Defining more than one constructor inside a class, but parameter should be differ in the following
ways:
1. no. of parameters
2. type of parameters
3. order of parameters
class Student
{
int id;
String name;
int age;
Student(int i,String n)
{
id = i;
10. name = n;
}
Student(int i,String n,int a)
{
11. id = i;
12. name = n;
13. age=a;
}
void display()
{
14. System.out.println(id+" "+name+" "+age);
}
public static void main(String args[])
{
15. Student s1 = new Student5(111,"Karan");
16. Student s2 = new Student5(222,"Aryan",25);
17. s1.display();
18. s2.display();
19. }
}
• Each class member function contains an implicit reference of its class type, named this
• It contains the address of the object through which the function is invoked
– this can be used to refer instance variables when there is a clash with local variables or
method arguments
– this can be used to call overloaded constructors from another constructor of the same
class
1. To overcome shadowing and allow a parameter or local variable to be the same name as an
instance field
class Student
24. {
25. String name;
26.
27. setName(String name)
28. {
29. this.name=name;
30. }
31. }
32.
2.To call a constructor from another constructor of the same class
class Sample
{
Sample()
{
this("Java"); // calls overloaded constructor
System.out.println("No Arg constructor ");
}
Sample(String str)
{
System.out.println("One argument constructor "+ str);
}
}
Static Memebers:
Static class members are the members of a class that do not belong to an instance of a class
They are shared by objects of same class.
Are initialized even before the instance variables are initialized and can be accessed even if the objects
are not created.
We can apply java static keyword with variables, methods, blocks and nested class.
We can access static members directly by prefixing the members with the class name
ClassName.staticVariable
ClassName.staticMethod(...)
Static variables:
Student(int r,String n)
10. {
11. rollno = r;
12. name = n;
13. }
14. void display ()
15. {
16. System.out.println(rollno+" "+name+" "+college);
17. }
18.
19. public static void main(String args[]){
20. Student8 s1 = new Student8(111,"Karan");
21. Student8 s2 = new Student8(222,"Aryan");
22.
23. s1.display();
24. s2.display();
25. }
26. }
Static methods:
• Static methods can only access directly the static members and manipulate a class’s static
variables
• A static method can be invoked without the need for creating an instance of a class.
• Static methods cannot access non-static members(instance variables or instance methods) of
the class
• Static method cant access this and super references
E.g
class Student
{
int rollno;
String name;
static String college = "ITS";
Student(int r, String n)
{
rollno = r;
name = n;
}
void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
s1.display();
s2.display();
s3.display();
}
}
E.g 2
class Calculate
{
static int cube(int x)
{
return x*x*x;
}
1. The static method cannot use non static data member or call non-static method directly.
2. this and super cannot be used in static context.
class A
{
int a=40;//non static
Arrays:
Arrays are objects in Java that store multiple variables of the same type.
Arrays can hold either primitives or object references, but the array itself will always be an
object on the heap
Abstraction:
Abstraction denotes essential characteristics of an object that distinguish it from all other kinds of
objects and thus provide crisply defined conceptual boundaries, relative to the perspective of the
viewer.
-Grady Booch
Abstraction is the process of taking only a set of essential characteristics from something.
Example
Encapsulation:
- Grady Booch
Encapsulation is binding data and operations that work on data together in a construct.
We can create a fully encapsulated class in java by making all the data members of the class private. Now
we can use setter and getter methods to set and get the data in it.
Student Rectangle LinkedList
-roll: long -length: int -Node
-name: String -width:int
+ addFirst(Node n)
+ display(): void +area(): int + remove(Node n)
+ read(): boolean + add(Node n, int pos)
-: private
+: public
Encapsulation is:
Binding the data with the code that manipulates it.
It keeps the data and the code safe from external interference
Advantage of Encapsulation in java
By providing only setter or getter method, you can make the class read-only or write-only.
It provides you the control over the data. Suppose you want to set the value of id i.e. greater
than 100 only, you can write the logic inside the setter method.
class Point {
private int x;
private int y;
return x;
return y;
}
class PointDemo {
int a, b;
p1.setX(22);
p1.setY(44);
a = p1.getX( );
b = p1.getY( );
}
Output :
The value of a is 22
The value of b is 24
Reuse in Object Oriented Language
Object Oriented Languages also implements reuse in the same way that we do in real life.
Using
has-a
is-a
Has-a or composition relationship is implemented by having a class having another class as its
member, or rather an object having another object as its member.
E.g of Has-A:
class Employee
{
int id;
String name;
Address address;//Address is a class
...
}
Inheritence:
Inheritance defines relationship among classes, wherein one class shares structure or behavior defined
in one or more classes.
- Grady Booch
Defines IS-A relationship between classes
Approach:
This generic class can then be used by more specific classes through inheritance.
Each of these specific classes can add things that are unique to it.
The class that is inherited is called super class and the class that is inheriting is called a subclass.
Student and Teacher are Person. Person can be a super class and Student and Teacher can be
subclass of Person class. Student is-a Person, Teacher is-a Person
HOD is-a Teacher. Since Teacher is-a Person, HOD is also a Person
SeminarHall is a ClassRoom
Syntax:
E.g
E.g.
class A {
int m, n;
void display1( ){
System.out.println("m and n are:"+m+" "+n);
}
}
class B extends A {
int c;
void display2( ){
System.out.println("c :" + c);
}
void sum(){
System.out.println("m+n+c = " + (m+n+c));
}
}
class InheritanceDemo {
public static void main(String args[ ]) {
A s1 = new A();
B s2 = new B();
s1.m = 10; s1.n = 20;
System.out.println("State of object A:");
s1.display1();
s2.m = 7; s2.n = 8; s2.c = 9;
System.out.println("State of object B:");
s2.display1();
s2.display2();
System.out.println("sum of m, n and c in object B is:");
s2.sum();
}
}
• But, it cannot directly access those members of the super class that have been declared as
private.
class A {
int money;
private int pocketMoney;
void fill(int money, int pocketMoney)
{
this.money = money;
this.pocketMoney = pocketMoney;
}
public int getPocketMoney()
{
return pocketMoney;
}
class B extends A {
private int total;
void sum( ) {
total = money + getPocketMoney();
}
public int getTotal() {
return total;
}
}
class AccessDemo
{
public static void main(String args[ ])
{
B subob = new B();
subob.fill(10,12);
subob.sum();
System.out.println("Total: " + subob.getTotal());
}
}
Super keyword:
• The creation and initialization of the super class object is a prerequisite to the creation of the
subclass object.
– The initialized superclass attributes are then inherited by the subclass object
• This is the only exception to the rule that a subclass inherits all the properties of its superclass
– The first is the call to the superclass’ constructor from the subclass constructor
– The second usage is to access a member of the superclass that has been overridden by a
subclass
• A subclass constructor can call a immediate superclass constructor by the following syntax:
– super(parameter-list);
e.g.
class Person {
Person(String name) {
this.name=name;
super(name);
this.empId=empId;
this.salary=salary;
class X {
X( ) {
System.out.println(“Inside X’s Constructor”);
}
}
class Y extends X {
Y( ) {
System.out.println(“Inside Y’s Constructor”);
}
}
class Z extends Y {
Z() {
System.out.println(“Inside Z’s Constructor”);
}
}
class Demo {
public static void main(String args[]) {
Z z = new Z();
}
}
• first line of a constructor must EITHER be a super (call on the super class constructor) OR a this
(call on the constructor of same class)
• If the first statement within a constructor is NEITHER super() NOR this(), then the compiler will
automatically insert a super(). (That is, invocation to the super class’ no argument constructor)
Polymorphism
A concept in type theory, according to which a name (such as a variable declaration) may denote
objects of many different classes that are related by some common super class; thus, any object
denoted by this name is able to respond to some common set of operations in different ways.
- Grady Booch
Polymorphism is the ability by which, we can create functions or reference variables which behaves
differently in different programmatic context.
This is used to write the program in such a way, that flow of control is decided in compile time itself. It is
achieved using method overloading.
In method overloading, an object can have two or more methods with same name, BUT, with their
method parameters different.
1. No of parameters
2. Type of parameters
3. Order of parameters
Exercises:
Create a class called Calculator which has 4 different methods add, diff, mul and div that accept two
numbers as parameters. Overload the methods such that the parameters can be of the following pattern.
c) First parameter is of int data type and second parameter is of double data type.
d) First parameter is of double data type and second parameter is of int data type
Create an object to access these methods and invoke these methods with different type of numbers
and display the result in the corresponding methods.
Overriding:
Redefinition of an inherited method declared in the super class by the subclass is called
Overriding.
Rules
1. The signature of the method (method name + argument list) must exactly match.
2. The return type must be same or a subtype of the return type of super class method
(covariant returns)
5. Instance methods can be overridden only if they are inherited/visible by the subclass.
e.g.
class Animal {
void makeNoise()
{
System.out.println("Some sound");
}
}
A reference variable of type super class can be assigned a reference to any subclass object derived from
that super class.
class A1 {
class A2 extends A1 {
class A3 {
A1 x;
A2 z = new A2();
x = new A2();//valid
z = new A1();//invalid
• Method overriding forms the basis of one of Java’s most powerful concepts: dynamic method
dispatch
• Dynamic method dispatch occurs when the Java language resolves a call to an overridden
method at runtime, and, in turn, implements runtime polymorphism
• Java makes runtime polymorphism possible in a class hierarchy with the help of two of its
features:
– overridden methods
Exercises:
Program 1:
Write a program to create a class named Shape. In this class we have three sub classes Circle, Triangle
and Square each class has one member function named draw(). Create these using polymorphism
concepts.
Program 2:
Create a super class called Figure that stores the dimensions of various two dimensional objects. Figure
defines a method called area( ) that computes the area of an object. The program derives two
subclasses from Figure. The two subclasses are Rectangle and Triangle. Each of these subclasses
overrides area( ) so that it returns the area of a Rectangle and a Triangle respectively.
The subclass which extends abstract class must provide the definition to
the abstract methods.
While an abstract class can have abstract methods, it could also NOT have
any abstract methods.
double dimension1;
double dimension2;
dimension1 = x;
dimension2 = y;
super(x,y); }
double area(){
}
Final keyword:
1. variable
2. method
3. class
final variables:
You cannot change the value of final variable (It will be constant).
i=20; //error
Note: In java constant is public static final field.
e.g
final methods:
e.g:
class A
{
final void m1() {
System.out.println(“m1 inside A”);
}
}
class B extends A
{
void m1() { // error, why bcoz m1() is final in side A. So we cannot override.
System.out.println(“m1 inside B”);
}
}
final classes:
e.g.
final class A{
Object class:
All classes in java, by default, inherit from a predefined java class called Object.
Object is a super class of all other classes; i.e., Java’s own classes(predefined classes), as well as
user-defined classes
This means that a reference variable of type Object can refer to an object of any other class
Object defines the following methods, which means that they are available in every object
Class A
{
Class B extends A {
Object
B
Method Description
public final Class getClass() returns the Class class object of this object. The Class class can
further be used to get the metadata of this class.
public int hashCode() returns the hashcode number for this object.
public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws creates and returns the exact copy (clone) of this object.
CloneNotSupportedException
public final void notify() wakes up single thread, waiting on this object's monitor.
public final void notifyAll() wakes up all the threads, waiting on this object's monitor.
public final void wait(long timeout)throws causes the current thread to wait for the specified milliseconds,
InterruptedException until another thread notifies (invokes notify() or notifyAll()
method).
public final void wait(long timeout,int causes the current thread to wait for the specified milliseconds
nanos)throws InterruptedException and nanoseconds, until another thread notifies (invokes notify()
or notifyAll() method).
public final void wait()throws causes the current thread to wait, until another thread notifies
InterruptedException (invokes notify() or notifyAll() method).
protected void finalize()throws Throwable is invoked by the garbage collector before object is being
garbage collected.
Packages
package package_name[.package_name];
Packages are named like variables except that they are all in lower case and
can contain dots (.)
e.g
package com;
class A {
System.out.println(“hello”);
Where to save?
Create a folder with same name as package name (here create a folder called
com )
e.g
Create a folder com inside E:\myprograms and save the file A.java inside com.
Compilation:
E:\>myprograms>javac com\A.java
Execution:
E:\>myprograms>java com.A
Need of Packages:
• Packages are containers used to store the classes and interfaces into
manageable units of code.
• Packages also help control the accessibility of your classes. This is also
called as visibility control.
• That is, whether other classes can access the class in the package depends
on the access specifiers used in its class declaration
– private
– protected
– public
Specifier Accessibility
Specifier Accessibility
• Whenever you need to access a class, you access it through its package by
prefixing the class with the package name
package com.abc;
public Class A {
package com.main;
class Test
// accessing class A
a1.m1();
package main;
import com.abc.A;
class Test
// accessing class A
A a1=new A();
a1.m1();
}
• It can be made easy by giving a star(*) at the end of the import statement.
For example:
import package1.*;
e.g.
A.java
package com.abc
public class A{
B.java
package com.abc
public Class B {
Test.java
package com.main;
import com.abc.*;
class Test {
{
A a1=new A();
B b1=new B();
Inbuilt Packages
– java.lang
– java.io
– java.util
– java.awt
The default package is java.lang. (String, System, Integer etc. classes are
inside java.lang package)
Access specifies:
}
class A { // with default access
}
private class A { // error, only public and default allowed
}
- Class members (variables & methods) can have all access levels.
Class Access:
class A {
void m1() {
}
}
class B
{
void test() {
A a=new A(); // class B accessing class A
}
}
2. Using inheritance
class A {
1. obj.{class_member}
2. through inheritance
Exercises:
Program 1:
Var1 as private;
Var2 as default;
Var3 as protected;
Var4 as public;
Try to access all 4 variables of the foundation class and see what variables are
accessible and what are not accessible.
Program 2:
Create a new project in which create a package named org.animals. In that create
various classes like Lion, Monkey, and Elephant. In each class create data
members like color, weight and age. Create methods like isVegetarian, canClimb,
getSound.
Create a package called zoo and create a class called VandalurZoo and create
objects for the animals that are existing in zoo and print the characteristic of each
animal.
Interface:
What is interface?
All the methods that are declared within an interface are always, by
default, public and abstract
e. g.
interface MyInterface {
void sayHello();
e.g:
void area();
Circle(double r){radius=r;}
System.out.println(Shape.PI+ “ “+ Circle.PI);
• Interface is also used to define the contract for the classes to implement.
• Interfaces are used to describe behaviors that are not specific to any
particular kind of object, but common to several kind of objects
Rules:
Interface I1
{
Void m1();
}
Interface I2 {
Void m2();
}
Class MyClass implements I1,I2 {
Public void m1() {
}
Public void m2() {
}
}
A class can extend only one class, but implement many interfaces.
Interface I1 {
}
Interface I2 {
}
Class A {
}
Class B extends A implements I1, I2 {
. Interface I1 {
}
Interface I2 extends I1 {
}
Marker interface:
– java.io.Serializable
– java.rmi.Remote
Exercises:
Program 1:
Define two classes Guitar and Piano that implements Playable interface and
implements play () method.
Define a class TestInstrument with main () method and instantiate both the
classes and test the code.
Expected output:
Program 2:
E= MC2
Make sure those constants names are used without repeating interface names
with constants (Hint: use static imports).