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

Unit - II

WHAT ARE Objects?


 An object has:
 –state - descriptive characteristics
 –behaviors - what it can do (or what can be done
to it)
 The state of a bank account includes its account
number and its current balance•
 The behaviors associated with a bank account
include the ability to make deposits and
withdrawals
 Note that the behavior of an object might change
its state. For example: chair, pen, table, keyboard,
bike etc. It can be physical and logical.
•A class is the blueprint of an object
•The class uses methods to define the behaviors
of the object
•The class that contains the main method of a
Java program represents the entire program
•A class represents a concept, and an object
represents the embodiment of that concept
•Multiple objects can be created from the same
class
Syntax to declare a class:
class <class_name>
{
data member;
method;
}
class Student1{
int id; //data member (also instance variabl
e)
String name; //data member(also instance variable)

void getId(); //member function

public static void main(String args[])


{
Student1 s1=new Student1();
//creating an object of Student
System.out.println(s1.id);
System.out.println(s1.name);
s1.getId();
}
Advantage of Method
•Code Reusability
•Code Optimization
 Javanaming convention is a rule to
follow as you decide what to name
your identifiers such as class,
package, variable, constant, method,
etc.
Identifiers Naming Rules Examples
Type
Class It should start with the public
uppercase letter. class Employee
It should be a noun {
such as Color, Button, //code
System, Thread, etc. }
Use appropriate words,
instead of acronyms.
Metho It should start with class Employee
d lowercase letter. {
It should be a verb such // method
as main(), print(), void draw()
println(). {
If the name contains //code snippet
multiple words, start it }
with a lowercase letter }
followed by an
uppercase letter such as
actionPerformed().
Variable It should start with a lowercase class Employee
letter such as id, name. {
It should not start with the special // variable
characters like & (ampersand), $ int id;
(dollar), _ (underscore). //code snippet
If the name contains multiple }
words, start it with the lowercase
letter followed by an uppercase
letter such as firstName,
lastName.
Avoid using one-character
variables such as x, y, z.
 Theaccess modifiers in Java specifies the
accessibility or scope of a field, method,
constructor, or class.
 We can change the access level of fields,
constructors, methods, and class by
applying the access modifier on it.
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is
only within the class. It cannot be accessed from
outside the class.
2. Default: The access level of a default modifier is
only within the package. It cannot be accessed
from outside the package. If you do not specify
any access level, it will be the default.
3. Protected: The access level of a protected
modifier is within the package and outside the
package through child class. If you do not make the
child class, it cannot be accessed from outside the
package.
4. Public: The access level of a public modifier is
everywhere. It can be accessed from within the
class, outside the class, within the package and
outside the package.
 A constructor in Java is a special
method that is used to initialize objects.
 The constructor is called when an object
of a class is created.
 It can be used to set initial values for
object attributes:
 The java command-line argument is an
argument i.e. passed at the time of running the
java program.
 The arguments passed from the console can be
received in the java program and it can be used
as an input.
In this example, we are receiving only one
argument and printing it.
To run this java program, you must pass at least
one argument from the command prompt.
class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}
 compile by > javac CommandLineExample.java
 run by > java CommandLineExample sonoo

Output:
Your first argument is: sonoo
 The this keyword refers to the current object in a
method or constructor.
 The most common use of the this keyword is to
eliminate the confusion between class attributes and
parameters with the same name
 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 final keyword is a non-access modifier used for
classes, attributes and methods, which makes them
non-changeable (impossible to inherit or override).
 The final keyword is useful when you want a variable
to always store the same value, like PI (3.14159...).
 The final keyword is called a "modifier".
 The static keyword in Java is used for memory
management mainly.
 We can apply static keyword with variables, methods,
blocks and nested classes.
 If you declare any variable as static, it is known as a
static variable.
 The static variable can be used to refer to the
common property of all objects (which is not unique
for each object), for example, the company name of
employees, college name of students, etc.
 The static variable gets memory only once in the
class area at the time of class loading.
 A class which contains the abstract keyword in its
declaration is known as an abstract class.
 An abstract class is a class that is declared abstract
means it may or may not include abstract methods.
 Abstract classes may not be marked as private or final.
abstract class syntax

public abstract class DemoClass


{
//declare other methods and fields
}
 The abstract keyword is a non-access modifier, used
for classes and methods. Class:
 An abstract class is a restricted class that cannot be
used to create objects (to access it, it must be inherited
from another class).
 Method: An abstract method can only be used in an
abstract class, and it does not have a body.
 The Finalize method is used to perform
cleanup operations on unmanaged
resources held by the current object before
the object is destroyed.
 The method is protected and therefore is
accessible only through this class or through a
derived class.
 Finalize() is the method of Object class.
 This method is called just before an object is garbage
collected.
 finalize() method overrides to dispose system
resources, perform clean-up activities and minimize
memory leaks.
 If a class has multiple methods having same name but
different in parameters, it is known as Method
Overloading.

Advantage of method overloading


 Method overloading increases the readability of the
program.
Different ways to overload the method
There are two ways to overload the method in
java
 By changing number of arguments
 By changing the data type
1) Method Overloading: changing no. of arguments
 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
2) Method Overloading: changing data type of
arguments
 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
 Inheritance in Java is a mechanism in which one
object acquires all the properties and behaviors of a
parent object. It is an important part of OOPs
(Object Oriented programming system).
 The idea behind inheritance in Java is that you can
create new classes that are built upon existing classes.
 For Method Overriding
 For Code Reusability.
 Class: A class is a group of objects which have
common properties. It is a template or blueprint from
which objects are created.
 Sub Class/Child Class: Subclass is a class which
inherits the other class. It is also called a derived class,
extended class, or child class.
 Super Class/Parent Class: Superclass is the class from
where a subclass inherits the features. It is also called a
base class or a parent class.
 Reusability: As the name specifies, reusability is a
mechanism which facilitates you to reuse the fields and
methods of the existing class when you create a new
class. You can use the same fields and methods already
defined in the previous class.
class Subclass-name extends Superclass-name
{
//methods and fields
}

 The extends keyword indicates that you are making a


new class that derives from an existing class. The
meaning of "extends" is to increase the functionality.
 On the basis of class, there can be single, and
multilevel
When a class inherits another class, it is known as
a single inheritance.
In the example given below, Dog class inherits the
Animal class, so there is the single inheritance.
class Animal
{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal
{
void bark(){System.out.println("barking...");}
}
class TestInheritance
{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}
}
Output:

barking...
eating...
 When there is a chain of inheritance, it is
known as multilevel inheritance.
 As you can see in the example given below,
BabyDog class inherits the Dog class which
again inherits the Animal class, so there is a
multilevel inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
 Dynamic method dispatch is a mechanism by which a
call to an overridden method is resolved at runtime.
 This is how java implements runtime polymorphism.
 When an overridden method is called by a reference,
java determines which version of that method to
execute based on the type of object it refer to.
Upcasting in Java
 When Parent class reference variable refers
to Child class object, it is known as Upcasting.
 In Java this can be done and is helpful in scenarios
where multiple child classes extends one parent class.
 In those cases we can create a parent class reference
and assign child class objects to it.
 The super keyword in Java is a reference variable
which is used to refer immediate parent class object.
 Whenever you create the instance of subclass, an
instance of parent class is created implicitly which is
referred by super reference variable.
Usage of Java super Keyword
 super can be used to refer immediate parent class
instance variable.
 super can be used to invoke immediate parent class
method.
 super() can be used to invoke immediate parent class
constructor.

super is used to refer immediate parent class


instance variable.
class Animal
{
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
d.printColor();
}
}
Output:

black
white
 An interface is a reference type in Java. It is
similar to class. It is a collection of abstract
methods.
 A class implements an interface, thereby
inheriting the abstract methods of the
interface.
 The interface keyword is used to declare an
interface.
 Here is a simple example to declare an interface −
Example
/* File name : Animal.java */
interface Animal
{
public void eat();
public void travel();
}
 A class uses the implements keyword to
implement an interface.
 The implements keyword appears in the class
declaration following the extends portion of
the declaration.
/* File name : MammalInt.java */
public class MammalInt implements Animal
{
public void eat()
{ System.out.println("Mammal eats"); }
public void travel()
{ System.out.println("Mammal travels"); }
public int noOfLegs()
{ return 0; }
public static void main(String args[])
{
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
Mammal eats
Mammal travels
When implementation interfaces, there are several rules −
 A class can implement more than one interface at a
time.
 A class can extend only one class, but implement many
interfaces.
 An interface can extend another interface, in a similar
way as a class can extend another class.
 In java, an interface can extend another interface. When
an interface wants to extend another interface, it uses
the keyword extends.
 The interface that extends another interface has its own
members and all the members defined in its parent
interface too.
 The class which implements a child interface needs to
provide code for the methods defined in both child and
parent interfaces
interface ParentInterface
{ void parentMethod(); }

interface ChildInterface extends ParentInterface


{ void childMethod(); }

class ImplementingClass implements ChildInterface


{ public void childMethod()
{ System.out.println("Child Interface method!!"); }
public void parentMethod()
{
System.out.println("Parent Interface method!"); }
}
public class ExtendingAnInterface
{
public static void main(String[] args)
{
ImplementingClass obj = new ImplementingClass();
obj.childMethod();
obj.parentMethod();
}
}
Output
Child Interface method!!
Parent Interface method!
 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.
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.
Simple example of java package
 The package keyword is used to create a package in
java.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to access package from another
package?
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.
//save by A.java
package pack;
public class A
{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B
{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:
Hello
 If you import package.classname then only declared
class of this package will be accessible.

//save by A.java
package pack;
public class A
{
public void msg()
{System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;

class B{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:
Hello
 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.
//save by A.java
package pack;
public class A
{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B
{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:
Hello
 Note: If you import a package, subpackages will not
be imported.

 Note: The standard of defining package is


domain.company.package e.g. com.javatpoint.bean or
org.sssit.dao.
package com.javatpoint.core;
class Simple
{
public static void main(String args[])
{
System.out.println("Hello subpackage");
}
}
Let’s quickly compare these access modifiers.
 public – accessible everywhere
 protected – accessible in the same package and in sub-
classes
 default – accessible only in the same package
 private – accessible only in the same class
 Java.lang package contains the classes that are
fundamental to the design of the Java
programming language
 The package java.lang contains classes and
interfaces that are essential to the java
language. These includes:
 The package java.lang contains classes and
interfaces that are essential to the Java
programming language.
 This java.lang package contains Object,
Thread, String etc. Object class is the ultimate
super class of all classes in Java.
 Thread class that controls each thread in a
multi threaded program.
 Object, the ultimate superclass of all classes in java
 Thread, the class that controls each thread in a
multithread program
 Throwable, the superclass of all error and exception
classes in java.
 Classes for accessing system resources and other low-
level entities.
 Math, a class that provides mathematical methods
 String, that class is used to represent strings.
 The wrapper class in Java provides the
mechanism to convert primitive into
object and object into primitive.
 autoboxing and unboxing feature convert
primitives into objects and objects into
primitives automatically.
 The eight classes of the java.lang package are
known as wrapper classes in Java. The list of
eight wrapper classes are given below:
Primitive Type Wrapper class

boolean Boolean

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double
 The automatic conversion of primitive data
type into its corresponding wrapper class is
known as autoboxing,
 for example, byte to Byte, char to Character,
int to Integer, long to Long, float to Float,
boolean to Boolean, double to Double, and
short to Short.
//Java program to convert primitive into objects
//Autoboxing example of int to Integer
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer explicitl
Integer j=a;//autoboxing, now compiler will write Integer.valueO
internally
System.out.println(a+" "+i+" "+j);
}
}
Output

20 20 20
 The automatic conversion of wrapper
type into its corresponding primitive type
is known as unboxing.
 It is the reverse process of autoboxing.
//Java program to convert object into primitives
//Unboxing example of Integer to int
public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int explicitly
int j=a;//unboxing, now compiler will write a.intValue()
internally
System.out.println(a+" "+i+" "+j);
}
}
Output
333

You might also like