0% found this document useful (0 votes)
13 views

Classes and Objects

Non-primitive data types in Java refer to objects that are created from classes. They store groups of values and live in heap memory, while the reference variable pointing to them lives on the stack. When a non-primitive variable is declared, it holds the memory address of the object rather than the object itself. Constructors initialize objects upon creation and have the same name as the class. The this keyword refers to the current object within instance methods.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Classes and Objects

Non-primitive data types in Java refer to objects that are created from classes. They store groups of values and live in heap memory, while the reference variable pointing to them lives on the stack. When a non-primitive variable is declared, it holds the memory address of the object rather than the object itself. Constructors initialize objects upon creation and have the same name as the class. The this keyword refers to the current object within instance methods.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 92

Non-Primitive Datatypes

Non Primitive data typesReferenced Data


types or object references
• Non-primitive data types are created by programmers.
• They are not predefined in java like primitive data types.
• These data types are used to store a group of values or several values.
• When we define a variable of non-primitive data types it
references a memory location where data is stored in the heap
memory.
• The object reference variable lives on the stack object reference
memory and the object to which it points always lives variable
on the heap memory.
• The stack holds a pointer to the object on the heap.

All non-primitive data types are simply called objects which are created by instantiating a
class.
How to Declare Non-primitive type Data type?
• An object reference variable is declared just like we declare a
primitive variable.

• Here, DT9 is the name of a class, and “s” is the name of a reference variable.
No object has yet been created.
• Create an object of a class using new keyword (used for creating the
memory in java.).

• creates an object of a class DT9 and assigns it to the reference variable “s”.
• DT9() ➞ Constructor of the class.
• The constructor of a class is generally used to initialize an object.
Key Points
• The default value of any reference variable is null.
• Whenever a non-primitive data type is passed to a method,
we are actually passing an address of that object where
data is stored.
Memory Allocation of Object & Object
Reference Variable
• A variable whose type is a
class, does not actually hold SITE
an object
• It holds the memory location of
an object.
• Creating an object means
storing data in memory.
• So, s is an reference variable
which refers an object
Declaring reference variable for Box object
Assigning Object Reference Variables
• Object reference variables act differently than you
might expect when an assignment takes place

• b1 and b2 will both refer to the same object.


• The assignment of b1 to b2 did not allocate any
memory or copy any part of the original object.
• It simply makes b2 refer to the same object as does Assigning one object reference
b1. variable to another object
• Any changes made to the object through b2 will reference variable only a
affect the object to which b1 is referring, since they copy of the Reference is made
are the same object. and not object
Assigning Object Reference Variables
• b1 and b2 both refer to the same object, they are not linked in any
other way.

• A subsequent assignment to b1 will simply unhook b1 from the


original object without affecting the object or affecting b2
• Here, b1 has been set to null, but b2 still points to the original object.
Java Methods
• type specifies the type of data • If the method does not return a value, its return
returned by the method. type must be void.
• Eg: int, char, double, class, String, • Methods that have a return type other than
or float.
void return a value to the calling routine using
• The name of the method is specified
the following form of the return statement:
by name.
• The parameter-list is a sequence of
type and identifier pairs separated by
commas. • Here, value is the value returned.
• Parameters are essentially
variables that receive the value
of the arguments passed to the
method when it is called. Methods are accessed using
• If the method has no parameters, reference variable using dot
then the parameter list will be
empty. operator b1.disp();
Accessing members of the class

Inside the class Outside the class


• Members of the class can access • Other class members can access
its members normally(without its members using dot operator
using dot operator)
Accessing members of the class
Parameter vs argument
• Parameter: A variable defined by a
method that receives a value when the
method is called
• An argument is a value that is passed
to a method when it is invoked

Parameter or Formal
arguments

Argument or actual
arguments
Exercise
• Write a java program to find the square root of the given number
using classes and objects
Constructors
• constructor initializes an object immediately upon creation
• It has the same name as the class in which it resides and is
syntactically similar to a method
• Once defined, the constructor is automatically called immediately
after the object is created, before the new operator completes
• The implicit return type of a class’ constructor is the class type itself
• Constructor’s job to initialize the internal state of an object
• the code creating an instance will have a fully initialized, usable object
immediately.
This is the reason
why the parentheses
are needed after the
class name
Rules for Writing Constructors in Java
• The name of the constructor must be the same as the name of its
class.
• A constructor must have no return type.
• It can not have not even void as its return type.
• We can use the access modifiers with a constructor to control its
access so that other classes can call the constructor.
• We can not declare a constructor as final, abstract, abstract and
synchronized.
Default constructor
The default constructor
automatically initializes
all instance variables to
zero.

Once you define your


own constructor, the
default constructor is
no longer used.

When you do not


explicitly define a
constructor for a class,
then Java creates a
default constructor for
the class
Parameterized Constructors
• Constructors with parameters, passing the values for instance
variables while creating objects

Parameter less
constructor

Parameterized
constructor
Creates box
with specified
dimensions

Creates boxes
with different
dimensions
The this Keyword
• A method will need to refer to the object that invoked it.
• this can be used inside any method to refer to the current object.
• this is always a reference to the object on which the method was
invoked.
• this can be used anywhere a reference to an object of the current
class’ type is permitted.
When this?? To avoid Instance Variable Hiding
• Names of the Local variables, including formal parameters to
methods can overlap with the names of the class’ instance variables.
• when a local variable has the same name as an instance variable,
the local variable hides the instance variable
So use different names for Use this keyword to refer
local variables, parameters
and instance variables
OR directly to the object
invoking the method,

this Resolve any


namespace collisions
between instance
variables and local
variables
• Class Add{}a1, a2
• a3=null;
• Add a1=new Add();//Sum
• No of objects=2
• Add a2=new Add();//Sum2
• No of References to Sum=a1
• Object references 2
• Add a3=a2; • No of References to Sum2=a2
• No of objects=2 • a2=null;
• No of References to Sum=a1 • No of objects=2
• No of References to • No of References to Sum=a1
Sum2=a2,a3 • No of References to Sum2=0
• No of objects=1
• No of References to Sum=a1
• No of References to Sum2=0
How dynamically created objects are deallocated??
Garbage collection:
• When no references to an object exist, that object is assumed to be
no longer needed, and the memory occupied by the object can be
reclaimed.
• It will not occur simply because one or more objects exist that are no
longer used.
Different Java run-time
implementations will
take varying approaches
to garbage collection
The finalize( ) Method
• An object can hold some non-Java resource such as a file handle or
character font
• To make sure these resources are freed before an object is destroyed
finalization is used
• By using finalization, you can define specific actions that will occur
when an object is just about to be reclaimed by the garbage
collector.
• To add a finalizer to a class, define the finalize( ) method as follows:
Prevents access
to finalize( ) by
code defined
outside its class
It is not called when
How finalize will work an object goes out-
of-scope

• The Java run time calls that method whenever it is about to recycle
an object of that class.
• Inside the finalize( ) method, specify those actions that must be
performed before an object is destroyed.
• The garbage collector runs periodically, checking for objects that are
no longer referenced by any running state or indirectly through other
referenced objects.
• Right before an asset is freed, the Java run time calls the finalize( )
method on the object.
Method Overloading
• Java allows to define two or more methods within the same class that
share the same name, as long as their parameter declarations are
different
• Method overloading is one of the ways that Java supports
polymorphism
• When an overloaded method is invoked, Java uses the type and/or
number of arguments to determine which version of the overloaded
method to actually call.
Overloaded methods must
differ in the type and/or
number of their
parameters.
Overloading Constructors

• Constructors can be
overloaded with
different arguments
Using Objects as Parameters to methods
• It is common in java to pass objects to methods

Test object
is passed
as
parameter
This will
create a copy
of a2 in a3
Passing objects to constructor

This will
create a copy
of a2 in a1[2]
Returning Objects
• method can return
any type of data,
including class
types
Recursion
• Java supports recursion.
• Recursion is the process of defining something in terms of itself.
• As it relates to Java programming, recursion is the attribute that
allows a method to call itself.
• A method that calls itself is said to be recursive
fact() calls itself until

Factorial of a number the condition is false


• Write a java program to print the fibonaci series using recursive
function
Access Control
• Encapsulation links data with the code that manipulates it
• Encapsulation, allows to control what parts of a program can access
the members of a class.
• By controlling access, prevents misuse.
• How a member can be accessed is determined by the access
modifier attached to its declaration
Java’s access modifiers Default access
modifier is public

• public, private, and protected


• When a member of a class is modified by public, then that member can be
accessed by any other code.
• When a member of a class is specified as private, then that member can
only be accessed by other members of its class.
• When a member of a class is specified as protected, then that member can
only be accessed by sub class and other members of its class
• When no access modifier is used, then by default the member of a class is
public within its own package, but cannot be accessed outside of its
package
Allows access to a
Static keyword class member
without objects

• Used to define a class member that will be used independently of


any object of that class
• Allows to create a member that can be used by itself, without
reference to a specific instance
• To create such a member, precede its declaration with the keyword
static
• static member can be accessed before any objects of its class are
created, and without reference to any object.
• Declare both methods and variables to be static.
Static variables
• Instance variables declared as static are, essentially, global variables.
• When objects of its class are declared, no copy of a static variable is
made.

All instances of the


class share the same
static variable
static Methods
• They can only directly call other static methods.
• They can only directly access static data.
• They cannot refer to this or super in any way.
• If you need to do computation in order to initialize your static
variables, you can declare a static block that gets executed exactly
once, when the class is first loaded.
Accessing static member outside the class
• static methods and variables can be used independently of any
object, outside of the class in which they are defined.
• specify the name of their class followed by the dot operator as below:

• Static variable can be accessed in same way as:

• Here, classname is the name of the class in which the static method is
declared
Final keyword
• A field can be declared as final to prevents its contents from being
modified, making it, essentially, a constant.
• So it must be initialized when it is declared in any of these ways:
• Give it a value when it is declared.
• Assign it a value within a constructor
• Its common coding convention to choose all uppercase identifiers for
final fields
Accessing final field
Nested and Inner Classes
• Nested Class: A class within another class;
• The scope of a nested class is bounded by the scope of its enclosing class
• A nested class has access to the members, including private members, of the
class in which it is nested
• However, the enclosing class does not have access to the members of the nested class
• A nested class that is declared directly within its enclosing class scope is a
member of its enclosing class.
• It is also possible to declare a nested class that is local to a block.
Two types of nested classes:Static vs non-static
Static class Non-static class
• A static nested class is one that • An inner class is a non-static
has the static modifier applied. nested class.
• It must access the non-static • Has access to all of the variables
members of its enclosing class and methods of its outer class
through an object.
• That is, it cannot refer to non-
directly
static members of its enclosing • inner classes can be declared
class directly. within any block scope
• Because of this restriction, static
nested classes are seldom used.
An instance of Inner
can be created only
within the scope of
class Outer.

Inner class refer to the


outer class members
directly in the same way
that other non-static
members
y is local to
Inner class

Replace
Inner class inside a block
Inheritance
Inheritance
• Inheritance allows the creation of hierarchical classifications.
• A class that is inherited is called a superclassParent class
• The class that does the inheriting is called a subclassChild class
• A specialized version of a superclass.
• It inherits all of the members defined by the superclass and adds its own,
unique elements.
Inheriting a class
• Inherit a class using extends keyword

• Hierarchy of inheritance in which a subclass becomes a superclass of


another subclass
• A subclass cannot have more than one superclass

Java does not


support multiple
inheritance
Single Inheritance
• Write a java program to display the animal type, name and skin colour
Animal (type=domestic)
Cat(name, skin)
Member Access and Inheritance
• a subclass cannot access private members of the superclass
• Only the subclass can access the protected member of the superclass

A class member that has been declared as private will remain


private to its class. It is not accessible by any code outside its
class, including subclasses.
A Superclass Variable Can Reference a Subclass Object
• A reference variable of
a superclass can be
assigned a reference to
any subclass derived
from that superclass.

Its type of the


reference variable
not object

when a reference to a subclass object is


assigned to a superclass reference
variable, you will have access only to
those parts of the object defined by the
superclass
• Class Num{}
• Class Sum{
• Psvm()
• { int a;
• Num n;
•}
Using super
• Used when a superclass wants to keep the details of its
implementation to itself(its data members private)
• No way for a subclass to directly access or initialize these variables on its
own
• The super keyword refers to superclass (parent) objects.
• Used to call superclass methods, and to access the superclass
constructor.
• The most common use of the super keyword is to eliminate the
confusion between superclasses and subclasses that have methods
with the same name.
Invokes the
Boxweight1
Using super to Call Superclass Constructors
• A subclass can call a constructor defined by its superclass by use of
the following form of super:
• super(arg-list);
• arg-list specifies any arguments needed by the constructor in the
superclass
• Constructors can be overloaded, super( ) can be called using any form
defined by the superclass.
• The constructor executed will be the one that matches the arguments.
Using Super
Using super
• super( ) is passed an object of type BoxWeight—not of type Box.
• This still invokes the constructor Box(Box ob).
• A superclass variable can be used to reference any object derived
from that class.
• Thus, pass a BoxWeight object to the Box constructor.
• Of course, Box only has knowledge of its own members.
Super keyword to call the superclass member
• super. member
• Here, member can be either a method or an instance variable
Multilevel Inheritance
• ABCD
When Constructors Are Called
• When a class hierarchy is created, in what order are the constructors
for the classes that make up the hierarchy called?

In a class hierarchy, constructors are


called in order of derivation, from
superclass to subclass
Method Overriding
• In a class hierarchy, when a method in a subclass has the same name
and type signature as a method in its superclass,
• then the method in the subclass is said to override the method in the
superclass.
• When an overridden method is called from within its subclass, it will
always refer to the version of that method defined by the subclass.
• The version of the method defined by the superclass will be hidden.

Occurs only when the names


and the type signatures of the
two methods are identical.
Dynamic Method Dispatch
• Java implements run-time polymorphism
• Dynamic method dispatch is the mechanism by which a call to an
overridden method is resolved at run time, rather than compile
time.
• How it works?
• When an overridden method is called through a superclass reference,
• Java determines which version of that method to execute based upon the type of the
object being referred to at the time the call occurs
• this determination is made at run time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.
Method overriding
• Class A{
• inal Void dis()
•}
• Class B extends A{
• Void dis()
•}
if a superclass contains a method that is overridden
by a subclass, then when different types of objects
are referred to through a superclass reference
variable, different versions of the method are
executed.
Why Overridden Methods?
• Allows Java to support run-time polymorphism: it allows a general
class to specify methods that will be common to all of its derivatives,
while allowing subclasses to define the specific implementation of
some or all of those methods.

Allows the subclass the


“one interface, multiple flexibility to define its
methods” own methods, yet still
enforces a consistent
interface.
When to Override
• Method overriding is mandatory - if you implement an interface, you
must override its methods.
Rules for Overriding
• The argument parameter should be exactly the same as that of the overridden method.
• A method declared static cannot be overridden but can be re-declared.
• The return type should be the same or a subtype of the return type declared in the original
overridden method in the super class.
• A method declared final cannot be overridden.
• Constructors cannot be overridden.
• If a method cannot be inherited then it cannot be overridden.
• A subclass within the same package as the instance's superclass can override any superclass
method that is not declared private or final.
• A subclass in a different package can only override the non-final methods declared public or
protected.
• An overriding method can throw any uncheck exceptions, regardless of whether the overridden
method throws exceptions or not. However, the overriding method should not throw checked
exceptions that are new or broader than the ones declared by the overridden method. The
overriding method can throw narrower or fewer exceptions than the overridden method.
Sample Program
• Write a java program to implement the concept of method overriding
for finding the area of the given shape(Rectangle, triangle and
square).
Abstract class and methods
• To define a superclass that declares the structure of a given
abstraction without providing a complete implementation of every
methodAbstract class
• To create a superclass that only defines a generalized form that will
be shared by all of its subclasses Abstract class
• to ensure that a subclass does, override all necessary
methodsabstract method
• These methods are sometimes referred to as subclasser responsibility
because they have no implementation specified in the superclass
Abstract method
• To define a abstract method with no body as:

• Any class that contains one or more abstract methods must also be
declared abstract as follows

• There can be no objects of an abstract class


Rules for Abstract class
• Subclass of an abstract class must either implement all of the
abstract methods in the superclass, or be declared abstract itself.
• An abstract class cannot be directly instantiated with the new
operator
• Although abstract classes cannot be used to instantiate objects, they
can be used to create object references,
• Java’s approach to run-time polymorphism is implemented through the use of
superclass references
Methods declared
Using final to Prevent Overriding as final cannot be
overridden.

• To disallow a method from being overridden, specify final as a modifier at the start of its
declaration
• Final methods provides performance enhancement
• The compiler is free to inline calls to them because it “knows” they will not be overridden by a subclass.
• When a small final method is called, often the Java compiler can copy the bytecode for the subroutine directly
inline with the compiled code of the calling method, thus eliminating the costly overhead associated with a
method call.
• Inlining is an option only with final methods.
• Normally, Java resolves calls to methods dynamically, at run timelate binding.
• However, since final methods cannot be overridden, a call to one can be resolved at compile
timeearly binding.
Using final to Prevent Overriding
Using final to Prevent Inheritance
• Precede the class declaration with final.
• Declaring a class as final implicitly declares all of its methods as final, too
Points to remember
• It is illegal to declare a class as both abstract and final since an
abstract class is incomplete by itself and relies upon its subclasses to
provide complete implementations.

You might also like