Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Dr. Kamal Macwan, Assistant Professor, CSE, Nirma University

Download as pdf or txt
Download as pdf or txt
You are on page 1of 72

Dr.

Kamal Macwan,
Assistant Professor,
CSE, Nirma University
 Classes and objects are the two main aspects of
object-oriented programming.

 A class is a template for objects, and an object is an


instance of a class.

 When the individual objects are created, they inherit


all the variables and methods from the class.
 An object has three characteristics:

 State: represents the data (value) of


an object.

 Behavior: represents the behavior


(functionality) of an object such as
deposit, withdraw, etc.

 Identity: An object identity is


typically implemented via a unique
ID. The value of the ID is not visible
to the external user. However, it is
used internally by the JVM to identify
each object uniquely.
 An object is an instance of a class. A class is
a template or blueprint from which objects
are created. So, an object is the
instance(result) of a class.

 Object Definitions:
 An object is a real-world entity.
 An object is a runtime entity.
 The object is an entity which has state and
behavior.
 The object is an instance of a class.
 A class is a group of objects which have
common properties. It is a template or
blueprint from which objects are created. It is
a logical entity. It can't be physical.

 A class in Java can contain:


 Fields
 Methods
 Constructors
 Blocks
 Nested class and interface
Mango

<class> Banana

Fruit
Orange

Apple
 We create classes and use it from another
class.

 We can have multiple classes in different Java


files or single Java file. If you define multiple
classes in a single Java source file, it is a good
idea to save the file name with the class name
which has main() method.
//Java Program to demonstrate having the main method
in another class
//Creating Student class.

class Student{
int id;
String name;
}
//Creating another class TestStudent1 which contains the
main method
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
 There are 3 ways to initialize object in Java.
 By reference variable
 By method
 By constructor
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name=“Hitesh";
System.out.println(s1.id+" "+s1.name
}
}
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
class Rectangle{
int length;
int width;
void insert(int l, int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle1{
public static void main(String args[]){
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
 Anonymous simply means nameless. An
object which has no reference is known as an
anonymous object. It can be used at the time
of object creation only.

 new Student().CalculateResult(92,78,86);
 A constructor initializes an object when it is created. It has the
same name as its class and is syntactically similar to a method.
However, constructors have no explicit return type.

 Typically, you will use a constructor to give initial values to the


instance variables defined by the class, or to perform any other
start-up procedures required to create a fully formed object.

 All classes have constructors, whether you define one or not,


because Java automatically provides a default constructor that
initializes all member variables to zero. However, once you define
your own constructor, the default constructor is no longer used.
 class Class_Name
{
Class_Name()
{
}
}

 Java allows two types of constructors namely −


 No argument Constructors
 Parameterized Constructors
 As the name specifies the no argument constructors
of Java does not accept any parameters instead, using
these constructors the instance variables of a method
will be initialized with fixed values for all objects.

class Game
{ int balance;
Game()
{
balance = 100;
}
}
 Most often, you will need a constructor that accepts
one or more parameters. Parameters are added to a
constructor in the same way that they are added to a
method, just declare them inside the parentheses after
the constructor's name.

class Game
{ int balance;
Game(int Money)
{
balance = Money;
}
}
Game G = new Game(250);
 There can be a lot of usage of java this keyword. In java,
this is a reference variable that refers to the current
object.
 this can be used to refer current class instance variable.
 this can be used to invoke current class method
(implicitly)
 this() can be used to invoke current class constructor.
 this can be passed as an argument in the method call.
 this can be passed as argument in the constructor call.
 this can be used to return the current class instance from
the method.
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
}
class A{
void m(){System.out.println("hello m");}
void n(){
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
}
}
class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}
class B{ class A4{
A4 obj; int data=10;
B(A4 obj){ A4(){
this.obj=obj; B b=new B(this);
} b.display();
void display(){ }
System.out.println(obj.data); public static void main(Stri
ng args[]){
//using data member of A4 class A4 a=new A4();
}
} }
}
class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello java");}
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
 “Method overloading is a feature of Java in which
a class has more than one method of the same
name and their parameters are different.”

 In other words, we can say that Method


overloading is a concept of Java in which we can
create multiple methods of the same name in the
same class, and all methods work in different
ways. When more than one method of the same
name is created in a Class, this type of method is
called Overloaded Methods.
class CalculateSquare
{
public void square()
{
System.out.println("No Parameter Method Called");
}
public int square( int number )
{
int square = number * number;
System.out.println("Method with Integer Argument Called:"+square);
}
public float square( float number )
{
float square = number * number;
System.out.println("Method with float Argument Called:"+square);
}
public static void main(String[] args)
{
CalculateSquare obj = new CalculateSquare();
obj.square();
obj.square(5);
obj.square(2.5);
}
}
 Method overloading increases the readability of the program.

 Provides flexibility to programmers so that they can call the same


method for different types of data.

 Makes the code look clean.

 Reduces the execution time because the binding is done in


compilation time itself.

 Minimizes the complexity of the code.

 Reuse the code again, which saves memory.


There are two ways to overload the method in java
 By changing number of arguments
 By changing the data type
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));
}}
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));
}}
 Object as an argument is use to establish
communication between two or more objects
of same class as well as different class, i.e,
user can easily process data of two same or
different objects within function.

 In Java, When a primitive type is passed to a


method ,it is done by use of call-by-value .
Objects are implicitly passed by use of call-
by-reference.
 The final keyword in java is used to restrict the user. The java
final keyword can be used in many context. Final can be:
 variable
 method
 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
 If you make any variable as final, you cannot change
the value of final variable(It will be constant).

class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}
 Java final method
 If you make any method as final, you cannot override
it.

 Java final class


 If you make any class as final, you cannot extend it.
 Inheritance is an important pillar of OOP(Object-Oriented
Programming). It is the mechanism in java by which one class
is allowed to inherit the features(fields and methods) of
another class.
 Super Class: The class whose features are inherited is
known as superclass(or a base class or a parent class).

 Sub Class: The class that inherits the other class is


known as a subclass(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.

 The keyword used for inheritance is extends.


In Multilevel Inheritance, a
derived class will be
inheriting a base class and
as well as the derived class
also act as the base class to
other class. In the below
image, class A serves as a
base class for the derived
class B, which in turn serves
as a base class for the
derived class C.
The data members and member functions of base class
comes automatically in derived class based on the
access specifier but the definition of these members
exists in base class only. So when we create an object of
derived class, all of the members of derived class must
be initialized but the inherited members in derived class
can only be initialized by the base class’s constructor as
the definition of these members exists in base class
only. This is why the constructor of base class is called
first to initialize all the inherited members.
// base class
class Parent
{ // base class constructor
Parent()
{ System.out.println("Inside base class");
}
}

// sub class
class Child extends Parent
{ //sub class constructor
Child()
{ System.out.println("Inside sub class");
}
}

class Main {
// main function
public static void main(String args[]) { Output :
// creating object of sub class Inside base class
Child obj=new Child(); Inside sub class
}
}
 Overriding is a feature that allows a subclass or child
class to provide a specific implementation of a
method that is already provided by one of its super-
classes or parent classes. When a method in a
subclass has the same name, same parameters or
signature, and same return type(or sub-type) as a
method in its super-class, then the method in the
subclass is said to override the method in the super-
class.
 Method overriding is one of the way by which java
achieve Run Time Polymorphism. The version of a
method that is executed will be determined by the object
that is used to invoke it. If an object of a parent class is
used to invoke the method, then the version in the parent
class will be executed, but if an object of the subclass is
used to invoke the method, then the version in the child
class will be executed. In other words, it is the type of the
object being referred to (not the type of the reference
variable) that determines which version of an overridden
method will be executed.
// Base Class
class Parent {
void show()
{
System.out.println("Parent's show()");
}
}

// Inherited class
class Child extends Parent {
// This method overrides show() of Parent
@Override
void show()
{
System.out.println("Child's show()");
}
}

// Driver class
class Main {
public static void main(String[] args)
{
// If a Parent type reference refers Output :
Parent’s show()
// to a Parent object, then Parent's
// show is called
Parent obj1 = new Parent();
obj1.show();
Child’s show()
// If a Parent type reference refers
// to a Child object Child's show()
// is called. This is called RUN TIME
// POLYMORPHISM.
Parent obj2 = new Child();
obj2.show();
}
}
 Overriding and Access-Modifiers : The access
modifier for an overriding method can allow
more, but not less, access than the
overridden method. For example, a protected
instance method in the super-class can be
made public, but not private, in the subclass.
Doing so, will generate compile-time error.
 Final methods can not be overridden : If we
don’t want a method to be overridden, we
declare it as final.
 Data abstraction is the process of hiding certain
details and showing only essential information
to the user.

 Abstraction can be achieved with either abstract


classes or interfaces
 Abstract class: is a restricted class that cannot
be used to create objects (to access it, it must
be inherited from another class).

 Abstract method: can only be used in an


abstract class, and it does not have a body. The
body is provided by the subclass (inherited
from).
abstract class Animal {
public abstract void sound() { }

public void sleep()


{ System.out.println(“ Zzzzz…”);
}

From the example above, it is not possible to


create an object of the Animal class:
A java package is a group of similar types of
classes, interfaces and sub-packages.

Package in java can be categorized in two form,


built-in package and user-defined package.

There are many built-in packages such as java,


lang, awt, javax, swing, net, io, util, sql etc.

Here, we will have the detailed learning of


creating and using user-defined packages.
Advantage of Java Package

1) Java package is used to categorize the classes and


interfaces so that they can be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.


 There are three ways to access the package from
outside the package.

 import package.*;
 import package.classname;
 fully qualified name.
 If you use package.* then all the classes and
interfaces of this package will be accessible but not
subpackages.

 The import keyword is used to make the classes and


interface of another package accessible to the
current package.
 If you use fully qualified name then only declared
class of this package will be accessible. Now there
is no need to import. But you need to use fully
qualified name every time when you are accessing
the class or interface.

 It is generally used when two packages have same


class name e.g. java.util and java.sql packages
contain Date class.
 Like a class, an interface can have methods and
variables, but the methods declared in an interface are
by default abstract (only method signature, no body).

 Interfaces specify what a class must do and not how. It


is the blueprint of the class.

 If a class implements an interface and does not provide


method bodies for all functions specified in the
interface, then the class must be declared abstract.
To declare an interface, use interface keyword. It is
used to provide total abstraction. That means all
the methods in an interface are declared with an
empty body and are public and all fields are public,
static and final by default. A class that implements
an interface must implement all the methods
declared in the interface. To implement interface
use implements keyword.
 It is used to achieve total abstraction.

 Since java does not support multiple inheritance


in case of class, but by using interface it can
achieve multiple inheritance .

 It is also used to achieve loose coupling.

 Interfaces are used to implement abstraction. So


the question arises why use interfaces when we
have abstract classes?
 An interface can extend another interface in the
same way that a class can extend another class.
The extends keyword is used to extend an
interface, and the child interface inherits the
methods of the parent interface.
Abstract class Interface
1) Abstract class can have abstract Interface can have only
and non-abstract methods. abstract methods. Since Java 8, it
can have default and static
methods also.
2) Abstract class doesn't support Interface supports multiple
multiple inheritance. inheritance.
3) Abstract class can have final, non- Interface has only static and final
final, static and non-static variables.
variables.
4) Abstract class can provide the Interface can't provide the
implementation of interface. implementation of abstract class.

5) The abstract keyword is used to The interface keyword is used to


declare abstract class. declare interface
Abstract class Interface
6) An abstract class can extend An interface can extend another
another Java class and implement Java interface only.
multiple Java interfaces.

7) An abstract class can be extended An interface can be implemented


using keyword "extends". using keyword "implements".
8) A Java abstract class can have Members of a Java interface are
class members like private, protected, public by default.
etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

You might also like