Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views

Object Oriented Programming

This is object oriented programming course that should given to IT 2nd year student

Uploaded by

genawmigo20
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Object Oriented Programming

This is object oriented programming course that should given to IT 2nd year student

Uploaded by

genawmigo20
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 79

Chapter 2

Objects and Classes


• Java is an Object-Oriented Language.
• As a language that has the Object Oriented feature,
Java supports the following fundamental concepts:
Polymorphism

 Inheritance
 Encapsulation
 Abstraction
 Classes
Objects
Instance
Method
Message Parsing
Class - A class can be defined as a template/blue print that
describes the behaviors/states that object of its type support.
Object - An object is an instance of a class.
Objects have states and behaviors.
Example: A dog has states - color, name, breed as well as
behaviors -wagging, barking, and eating.
Objects in Java:
Let us now look deep into what are objects.
• If you compare the software object with a real
world object, they have very similar characteristics.
• Software objects also have a state and behavior.
• A software object's state is stored in fields and
behavior is shown via methods.
• So in software development, methods operate on
the internal state of an object and the object-to-
object communication is done via methods.
2.1. Defining a Class in Java
• Java provides a reserved keyword class to define a class.
• The keyword must be followed by the class name.
• Inside the class, we declare methods and variables.
A sample of a class is given below:
public class Dog{
String breed;
int age;
String color;
void barking(){
}
void hungry(){
}
void sleeping(){
}}
• In the above example, barking(), hungry() and sleeping() are
• A class can contain any of the following variable
types.
Local variables: Variables defined inside methods,
constructors or blocks are called local variables.
• The variable will be declared and initialized within the
method and the variable will be destroyed when the
method has completed.
Instance variables: Instance variables are variables
within a class but outside any method.
• These variables are instantiated when the class is
loaded.
• Instance variables can be accessed from inside any
method, constructor or blocks of that particular class.
Class variables: Class variables are variables declared
with in a class, outside any method, with the static
2.2. Creating an Object
• basically an object is created from a class.
• In Java, the new key word is used to create new
objects.
• There are three steps when creating an object from
a class:
• Declaration: A variable declaration with a variable
name with an object type.
• Instantiation: The 'new' key word is used to create
the object.\\create an instance
• Initialization: The 'new' keyword is followed by a
call to a constructor. \\ set its initial value
• This call initializes the new object.
Example of creating an object is given below:
public class Puppy{
public Puppy(String name){
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}
public static void main(String []args){
// Following statement would create an object myPuppy
Puppy myPuppy = new Puppy( "tommy" );
}
}
If we compile and run the above program, then it would
produce the following result:
Passed Name is :tommy
Declaring a Variable to Refer to an Object
 Previously, you learned that to declare a variable,
you write:
 type name;
 This notifies the compiler that you will use name to
refer to data whose type is type.
 With a primitive variable, this declaration also
reserves the proper amount of memory for the
variable.
 You can also declare a reference variable on its own
line.
For example:
Point originOne;
• If you declare originOne like this, its value will be
undetermined until an object is actually created and
assigned to it.
• Simply declaring a reference variable does not create
an object.
• For that, you need to use the new operator.
• You must assign an object to originOne before you
use it in your code. Otherwise, you will get a compiler
error.
• A variable in this state, which currently references no
object, can be illustrated as follows (the variable
name, originOne, plus a reference pointing to
nothing):
Instantiating a Class
• The new operator instantiates a class by allocating
memory for a new object and returning a reference
to that memory.
• The new operator also invokes the object
constructor.
• Note: The phrase "instantiating a class" means the
same thing as "creating an object."
• When you create an object, you are creating an
"instance" of a class, therefore "instantiating" a
class.
• The new operator requires a single, postfix
argument: a call to a constructor.
• The name of the constructor provides the name of
the class to instantiate.
• The new operator returns a reference to the object
it created.
• This reference is usually assigned to a variable of
the appropriate type, like:
Point originOne = new Point(23, 94);
• The reference returned by the new operator does
not have to be assigned to a variable.
Initializing an Object
Here's the code for the Point class:
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
• This class contains a single constructor.
• You can recognize a constructor because its
declaration uses the same name as the class and it
has no return type.
• The constructor in the Point class takes two integer
arguments, as declared by the code (int a, int b).
• The following statement provides 23 and 94 as
values for those arguments:
Point originOne = new Point(23, 94);
Here's the code for the Rectangle class, which contains
four constructors:
public class Rectangle {
public int width = 0;
public int height = 0;
public Point origin;
// four constructors
public Rectangle() {
origin = new Point(0, 0);
}
public Rectangle(Point p) {
origin = p;
}
public Rectangle(int w, int h) {
origin = new Point(0, 0);
width = w;
height = h;
}
public Rectangle(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}
// a method for moving the rectangle
public void move(int x, int y) {
origin.x = x;
origin.y = y;
}
// a method for computing the area of the
rectangle
public int getArea() {
return width * height;
}
}
• Each constructor lets you provide initial values for
the rectangle's origin, width, and height, using both
primitive and reference types.
• If a class has multiple constructors, they must have
different signatures.
• The Java compiler differentiates the constructors
based on the number and the type of the
arguments.
• All classes have at least one constructor.
• If a class does not explicitly declare any, the Java
compiler automatically provides a no-argument
constructor, called the default constructor.
Accessing Instance Variables and Methods
• Instance variables and methods are accessed via
created objects.
• To access an instance variable the fully qualified path
should be as follows:
/* First create an object */
ObjectReference = new Constructor();

/* Now call a variable as follows */


ObjectReference.variableName;

/* Now you can call a class method as follows */


ObjectReference.MethodName();
Example:
• This example explains how to access instance
variables and methods of a class:
public class Puppy{
int puppyAge;
public Puppy(String name){
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}
public void setAge( int age ){
puppyAge = age;
}
public int getAge( ){
System.out.println("Puppy's age is :" + puppyAge );
return puppyAge;
}
public static void main(String []args){
/* Object creation */
Puppy myPuppy = new Puppy( "tommy" );
/* Call class method to set puppy's age */
myPuppy.setAge( 2 );
/* Call another class method to get puppy's age */
myPuppy.getAge( );
/* You can access instance variable as follows as well */
System.out.println("Variable Value :" + myPuppy.puppyAge
); }}
• If we compile and run the above program, then it
would produce the following result:
Passed Name is :tommy
Puppy's age is :2
Variable Value :2
Nested Classes
• The Java programming language allows you to define a
class within another class. Such a class is called a
nested class and is illustrated here:
class OuterClass {
...
class NestedClass {
...
}
}
• Terminology: Nested classes are divided into two
categories: static and non-static.
• Nested classes that are declared static are called static
nested classes.
• Non-static nested classes are called inner classes.
class OuterClass {
... static class StaticNestedClass {
... }
class InnerClass {
... }}
• A nested class is a member of its enclosing class.
• Static nested classes do not have access to other
members of the enclosing class.
• Non-static nested classes (inner classes) have access to
other members of the enclosing class, even if they are
declared private.
• As a member of the OuterClass, a nested class can be
declared private, public, protected, or package
private(Default).
• (Remember that outer classes can only be declared
public or package private.)
2.5. Constructors and Methods
Constructors:
• Constructor is a block of code that initializes the
newly created object.
• When discussing about classes, one of the most
important sub topic would be constructors.
• Every class has a constructor.
• If we do not explicitly write a constructor for a class
the Java compiler builds a default constructor for
that class.
• Each time a new object is created, at least one
constructor will be invoked.
• The main rule of constructors is that they should
have the same name as the class.
• A class can have more than one constructor.
• Here are the key differences between a constructor
and a method:
• A constructor doesn’t have a return type.
• The name of the constructor must be the same
as the name of the class.
• Unlike methods, constructors are not considered
members of a class.
• A constructor is called automatically when a
new instance of an object is created.
Here’s the basic format for coding a constructor:
Public class ClassName
ClassName ( ) {
{
statements...
}
• Constructors have one purpose in life: to create an
instance of a class.
• This can also be called creating an object.
• The purpose of methods, by contrast, is much more
general.
• A method's basic function is to execute Java code.
Example of a constructor is given below:
public class Puppy{
public Puppy(){
}
public Puppy(String name){
// This constructor has one parameter, name.
}
}
Types of constructors
• There are three types of constructors: Default, No-
arg constructor and Parameterized.
Default constructor
• If you do not implement any constructor in your
class, Java compiler inserts a default constructor
into your code on your behalf.
• This constructor is known as default constructor.
• You would not find it in your source code (the java
file) as it would be inserted into the code during
compilation and exists in class file.
• This process is shown in the diagram below:
• Note: If you implement any constructor then you
no longer receive a default constructor from Java
compiler.
No-arg constructor:
• Constructor with no arguments is known as no-arg
constructor.
• The signature is same as default constructor;
• however body can have any code unlike default
constructor where the body of the constructor is
empty.
Example: no-arg constructor
class Demo
{
public Demo()
{
System.out.println("This is a no argument constructor");
}
public static void main(String args[]) {
new Demo();
}
}
• Output: This is a no argument constructor
Parameterized constructor
• Constructor with arguments (or you can say
parameters) is known as Parameterized constructor.
Example: parameterized constructor
• In this example we have a parameterized
constructor with two parameters id and name.
• While creating the objects obj1 and obj2 you have
passed two arguments so that this constructor gets
invoked after creation of obj1 and obj2.
public class Employee {
int empId;
String empName;
//parameterized constructor with two parameters
Employee(int id, String name){
this.empId = id;
this.empName = name;
}
void info(){
System.out.println("Id: "+empId+" Name: "+empName);
}
public static void main(String args[]){
Employee obj1 = new Employee(10245,"Chaitanya");
Employee obj2 = new Employee(92232,"Negan");
obj1.info();
obj2.info();
}
}
Output:
Id: 10245 Name: Chaitanya
Id: 92232 Name: Negan
Example2: parameterized constructor
• In this example, we have two constructors, a
default constructor and a parameterized
constructor.
• When we do not pass any parameter while creating
the object using new keyword then default
constructor is invoked, however when you pass a
parameter then parameterized constructor that
matches with the passed parameters list gets
invoked.
class Example2
{
private int var;
public Example2()
{
this.var = 10;
}
//parameterized constructor
public Example2(int num)
{
this.var = num;
}
public int getValue()
{
return var;
}
public static void main(String args[])
{
Example2 obj = new Example2();
Example2 obj2 = new Example2(100);
System.out.println("var is: "+obj.getValue());
System.out.println("var is: "+obj2.getValue());
}
}
Output:
var is: 10
var is: 100
Java Copy Constructor
 A copy constructor is used for copying the values of one object to another
object.
class JavaExample{
String web;
JavaExample(String w){
web = w;
}
/* This is the Copy Constructor, it
* copies the values of one object
* to the another object (the object
* that invokes this constructor)
*/
JavaExample(JavaExample je){
web = je.web;
}
void disp(){
System.out.println("Website: "+web);
}
public static void main(String args[])
{
JavaExample obj1 = new JavaExample("BeginnersBook");

/* Passing the object as an argument to the constructor


* This will invoke the copy constructor
*/
JavaExample obj2 = new JavaExample(obj1);
obj1.disp();
obj2.disp();
}
}
Output:
Website: BeginnersBook
Website: BeginnersBook
Methods
• Methods define behaviour.
• A method is a collection of statements that are
grouped together to perform an operation.
• System.out.println() is an example of a method.
• You can define your own methods to perform your
desired tasks.
• Let’s consider the following codes:
class Myclass
{
public static void sayHello()
{
System.out .println(“Hello world”);
}
Public static void main(String args[])
{
sayHello( );
}
}
• Output: Hello world
• The code above declares a method called
“sayHello()”, which prints a text, and then gets
called a main.
• To call a method, type its name and then follow the
name with a setoff parenthesis.
• You can call a method as many times as necessary.
• When a method runs, the code jumps down to
where the method is define, executes the code
inside of it, then goes back and proceeds to the
next line.
Example :
Class Myclass { static void sayHello()
{
System.out .println(“Hello world”);
}
Public static void main(String args[])
{ sayHello( );
sayHello( );
sayHello( );
}
}
Output:
Hello world
Hello world
Hello world
Method parameters
• You can also create a method that takes some data,
called parameters, along with it when you call it.
• For example, we can modify our sayHello( ) method
to take and output a string parameter.
class Myclass { public static void sayHello( String
name)
{
System.out .println(“Hello ”+ name);
}
Public static void main(String args[])
{ sayHello(“Abebe “);
sayHello(“Eden “);
}
}
Output:
HelloAbebe
Hello Eden
• The method above takes a String called name as a
parameter, which is used in the method’s body.
• Then when calling the method, we pass the
parameter’s value inside the parenthesis.
Advantage of using methods
• Code reuse: you can write a method once, and use
it multiple times, without having to write the code
each time.
• Parameters: based on the parameters passed in,
method can perform various actions.
2.6. Java Access Modifiers – Public, Private, Protected &
Default
• You must have seen public, private and protected keywords
while practicing java programs, these are called access
modifiers.
• An access modifier restricts the access of a class,
constructor, data member and method in another class.
• java has four access modifiers:
1. default
2. private
3. protected
4. public
1. Default access modifier
• When we do not mention any access modifier, it is called
default access modifier.
• The scope of this modifier is limited to the package only.
This means that if we have a class with the default access
modifier in a package, only those classes that are in this
package can access this class.
• No other class outside this package can access this class.
• Similarly, if we have a default method or data member in a
class, it would not be visible in the class of another package.
• Lets see an example to understand this:
Default Access Modifier Example in Java
• To understand this example, you must have the
knowledge of packages in java.
• In this example we have two classes, Test class is
trying to access the default method of Addition
class, since class Test belongs to a different
package, this program would throw compilation
error, because the scope of default modifier is
limited to the same package in which it is declared.
Addition.java
package abcpackage;
public class Addition {
/* Since we didn't mention any access modifier here, it would
* be considered as default.
*/
int addTwoNumbers(int a, int b){
return a+b;
}
}
Test.java
package xyzpackage;
/* We are importing the abcpackage
* but still we will get error because the
* class we are trying to use has default access
* modifier.
*/
import abcpackage.*;
public class Test {
public static void main(String args[]){
Addition obj = new Addition();
/* It will throw error because we are trying to access
* the default method in another package
*/
obj.addTwoNumbers(10, 21);
}
}
Output:
 compilation problem:
2. Private access modifier
The scope of private modifier is limited to the class
only.
1. Private Data members and methods are only
accessible within the class
2. Class and Interface cannot be declared as private
3. If a class has private constructor then you cannot
create the object of that class from outside of the
class.
• Let’s see an example to understand this:
Private access modifier example in java
• This example throws compilation error because we
are trying to access the private data member and
method of class ABC in the class Example.
• The private data member and method are only
accessible within the class.
class ABC{
private double num = 100;
private int square(int a){
return a*a;
}
}
public class Example{
public static void main(String args[]){
ABC obj = new ABC();
System.out.println(obj.num);
System.out.println(obj.square(10));
}
}
Output:
• Compile - time error
3. Protected Access Modifier
• Protected data member and method are only
accessible by the classes of the same package and
the subclasses present in any package.
• You can also say that the protected access modifier
is similar to default access modifier with one
exception that it has visibility in sub classes.
• Classes cannot be declared protected.
• This access modifier is generally used in a parent
child relationship.
Protected access modifier example in Java
• In this example the class Test which is present in
another package is able to call the
addTwoNumbers() method, which is declared
protected.
• This is because the Test class extends class Addition
and the protected modifier allows the access of
protected members
in subclasses (in any packages). Addition.java
package abcpackage;
public class Addition {
protected int addTwoNumbers(int a, int b){
return a+b;
}
}
Test.java
package xyzpackage;
import abcpackage.*;
class Test extends Addition{
public static void main(String args[]){
Test obj = new Test();
System.out.println(obj.addTwoNumbers(11, 22));
}
}
Output:
• 33
4. Public access modifier
• The members, methods and classes that are declared public can
be accessed from anywhere. This modifier doesn’t put any
restriction on the access.
public access modifier example in java
• Lets take the same example that we have seen above but this
time the method addTwoNumbers() has public modifier and
class Test is able to access this method without even extending
the Addition class.
• This is because public modifier has visibility everywhere.
• Addition.java
package abcpackage;
public class Addition {
public int addTwoNumbers(int a, int b){
return a+b;
}
}
Test.java
package xyzpackage;
import abcpackage.*;
class Test{
public static void main(String args[]){
Addition obj = new Addition();
System.out.println(obj.addTwoNumbers(100, 1));
}
}
Output:
• 101
• Lets see the scope of these access modifiers in tabular form:
The scope of access modifiers in tabular form
------------+-------+---------+--------------+--------------+--------
| Class | Package | Subclass | Subclass | Outside|
|| |(same package)| (diff package)| Class |
————————————+———————+—————————+——————————----+
—————————----—+————————
public | Yes | Yes | Yes | Yes | Yes |
————————————+———————+—————————+—————————----—+
—————————----—+————————
protected | Yes | Yes | Yes | Yes | No |
————————————+———————+—————————+————————----——+
————————----——+————————
default | Yes | Yes | Yes | No | No |
————————————+———————+—————————+————————----——+
————————----——+————————
private | Yes | No | No | No | No |
------------+-------+---------+--------------+--------------+--------
2.7 Encapsulation
• Encapsulation is one of the four fundamental OOP
concepts.
• The other three are inheritance, polymorphism,
and abstraction.
• Encapsulation in java is a process of wrapping code
and data together into a single unit,
• for example capsule i.e. mixed of several medicines.
• 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.
• It is the technique of making the fields in a class
private and providing access to the fields via
public methods.
• If a field is declared private, it cannot be accessed
by anyone outside the class, thus hiding the fields
within the class.
• For this reason, encapsulation is also referred to as
data hiding.
• Encapsulation can be described as a protective
barrier/block that prevents the code and data
being randomly accessed by other code defined
outside the class.
Advantage of Encapsulation in java
• A class can have total control over what is stored in
its fields.
• The users of a class do not know how the class
stores its data.
• A class can change the data type of a field and users
of the class do not need to change any of their
code.
• Example:
Let us look at an example that depicts encapsulation:
/* File name : EncapTest.java */
public class EncapTest{
private String name;
private String idNum;
private int age;
public int getAge(){
return age;
}
public String getName(){
return name;
}
public String getIdNum(){
return idNum;
}
public void setAge( int newAge){
age = newAge;
}
public void setName(String newName){
name = newName;
}
public void setIdNum( String newId){
idNum = newId;
}}
• The public methods are the access points to this class' fields from the outside java world.
• Normally, these methods are referred as getters and setters.
• Therefore any class that wants to access the variables should access them through these
getters and setters.
• The variables of the EncapTest class can be accessed as below::
/* File name : RunEncap.java */
public class RunEncap{
public static void main(String args[]){
EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
System.out.print("Name : " + encap.getName()+
" Age : "+ encap.getAge());
}}
• This would produce the following result:
• Name : James Age : 20

You might also like