0% found this document useful (0 votes)
12 views31 pages

Java OOP

Uploaded by

asherushare
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views31 pages

Java OOP

Uploaded by

asherushare
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JAVA OOP

Dr. HAMSA AJAY BHAT


Dr. SONALI CHAKRABORTY
DEPARTMENT OF MATHEMATICALAND COMPUTATIONAL SCIENCES
NATIONAL INSTITUTE OF TECHNOLOGY KARNATAKA
SURATHKAL, MANGALORE – 575025, INDIA
Dr. Sonali Chakraborty
INTRODUCTION

• Procedural programming is about writing procedures or methods that perform


operations on the data, while object-oriented programming is about creating objects
that contain both data and methods
• Object-oriented programming has several advantages over procedural
programming:

• OOP is faster and easier to execute


• OOP provides a clear structure for the programs
• OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the
code easier to maintain, modify and debug
• OOP makes it possible to create full reusable applications with less code and
shorter development time
CLASSES AND OBJECTS
Classes and objects are the two main aspects of object-oriented programming
Class: Fruit
Objects: Apple, Banana, Mango

Class: Car
Objects: Volvo, Audi, Toyota

When the individual objects are created, they inherit all the variables and methods
from the class
The car has attributes, such as weight and color, and methods, such as drive and brake

public class Test {


int x = 5;
}
CREATING AN OBJECT
• An object is created from a class
• Create an object called "myObj" and print the value of x:

public class Test


{
int x = 5;
public static void main(String[] args) {
Test myObj = new Test();
System.out.println(myObj.x);
}
}
CREATING MULTIPLE OBJECTS OF A CLASS
public class Test {
int x = 5;
public static void main(String[] args) {
Test myObj1 = new Test(); // Object 1
Test myObj2 = new Test(); // Object 2
System.out.println(myObj1.x);
System.out.println(myObj2.x);
}
}
USING MULTIPLE CLASSES
• Can also create an object of a class and access it in another class
• This is often used for better organization of classes (one class has all the attributes
and methods, while the other class holds the main() method (code to be executed))
class Second {
public static void main(String[] args) {
Test myObj = new Test();
System.out.println(myObj.x);
}
} • Save the file name same as class
name.java
public class Test • Test.java
{ • To compile: javac Test.java
int x = 5; • To execute: java Test.java
}
CLASS ATTRIBUTES
Class attributes are variables within a class

public class Test { public class Test {


int x = 5; int x = 5;
int y = 3; public static void main(String[]
} args) {
Test myObj = new Test();
Can access attributes by creating an object of System.out.println(myObj.x);
the class, and by using the dot syntax (.) }
}
Create an object of the Test class, with the
name myObj
Use the x attribute on the object to print its
value
MODIFY ATTRIBUTES
Set the value of x to 40

public class Test {


int x;
public static void main(String[] args) {
Test myObj = new Test();
myObj.x = 40;
System.out.println(myObj.x);
}
}
MULTIPLE ATTRIBUTES
public class Test {
String fname = “Anil";
String lname = “Kumar";
int age = 24;

public static void main(String[] args) {


Test myObj = new Test();
System.out.println("Name: " + myObj.fname + " " + myObj.lname);
System.out.println("Age: " + myObj.age);
}
}
JAVA CLASS METHODS
public class Test {
static void myMethod() {
System.out.println("Hello World!");
}
}
• myMethod() prints a text (the action), when it is called. To call a method, write the
method's name followed by two parentheses () and a semicolon;

public class Test {


static void myMethod() { Calling myMethod(): inside main
System.out.println("Hello World!");
}

public static void main(String[] args) {


myMethod();
}
}
STATIC VERSUS PUBLIC
• A static method means that it can be accessed without creating an object of the
class, unlike public, which can only be accessed by objects:
public class Test {
// Static method // Main method
static void myStaticMethod() { public static void main(String[] args)
System.out.println("Static methods can {
be called without creating objects"); myStaticMethod(); // Call the static
} method
// myPublicMethod(); This would
// Public method compile an error
public void myPublicMethod() { Test myObj = new Test(); // Create an
System.out.println("Public methods object of Main
must be called by creating objects"); myObj.myPublicMethod(); // Call the
} public method on the object
}
}
ACCESS METHOD WITH AN OBJECT
• Create a Car object named myCar. Call the fullThrottle() and speed() methods on
the myCar object

public class Test { // Inside main, call the methods on the


public void fullThrottle() { myCar object
System.out.println("The car is going as public static void main(String[] args) {
fast as it can!"); Test myCar = new Test(); // Create a
} myCar object
myCar.fullThrottle(); // Call the
// Create a speed() method and add a fullThrottle() method
parameter myCar.speed(200); // Call the
public void speed(int maxSpeed) { speed() method
System.out.println("Max speed is: " + }
maxSpeed); }
}
USING MULTIPLE CLASSES
public class Test { class Second {
public void fullThrottle() { public static void main(String[] args) {
System.out.println("The car is going as Test myCar = new Test(); // Create a
fast as it can!"); myCar object
} myCar.fullThrottle(); // Call the
fullThrottle() method
public void speed(int maxSpeed) { myCar.speed(200); // Call the
System.out.println("Max speed is: " + speed() method
maxSpeed); }
} }
}
JAVA CONSTRUCTORS
• Constructors play an important role in object creation
• A constructor is a special block of code that is called when an object is created
• Its main job is to initialize the object, to set up its internal state, or to assign default
values to its attributes
• This process happens automatically when we use the "new" keyword to create an
object
❑ Characteristics of Constructors:
• Same Name as the Class: A constructor has the same name as the class in which
it is defined
• No Return Type: Constructors do not have any return type, not even void. The
main purpose of a constructor is to initialize the object, not to return a value

• Automatically Called on Object Creation: When an object of a class is created,


the constructor is called automatically to initialize the object’s attributes

• Used to Set Initial Values for Object Attributes: Constructors are primarily
used to set the initial state or values of an object’s attributes when it is created
EXAMPLE
import java.io.*; // Driver Class super() is used to explicitly invoke the
class Test { constructor of the immediate parent class
// Constructor (superclass) from within the constructor of
Test() a subclass. This invocation must be the
{ very first statement within the subclass's
super(); constructor
System.out.println("Constructor
Called"); It is not necessary to write a constructor for
} a class
// main function It is because the Java compiler creates a
public static void main(String[] args) default constructor (constructor with no
{ arguments) if your class doesn't have any
Test t= new Test();
}
}
CONSTRUCTOR VERSUS METHODS
Features Constructor Method
Name Constructors must have the Methods can have any valid
same name as the class name name
Return Type Constructors do not return Methods have the return type
any type or void if does not return any
value.
Invocation Constructors are called Methods are called explicitly
automatically with new
keyword
Purpose Constructors are used to Methods are used to perform
initialize objects operations
WHEN JAVA CONSTRUCTOR IS CALLED
• The first line of a constructor is a call to super() or this()
• Each time an object is created using a new() keyword, at least one constructor (it
could be the default constructor) is invoked to assign initial values to the data
members of the same class
• Rules for writing constructors are as follows:
✓ The constructor of a class must have the same name as the class name in which it
resides
✓ A constructor in Java can not be abstract, final, static, or Synchronized
✓ Access modifiers can be used in constructor declaration to control its access i.e
which other class can call the constructor
TYPES OF CONSTRUCTOR
❑ Types of Constructors in Java
Primarily there are three types of constructors in Java are mentioned below:
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor

1. Default Constructor
• A constructor that has no parameters is known as default constructor
• A default constructor is invisible
• And if we write a constructor with no arguments, the compiler does not create a
default constructor
• Once a constructor is defined (with or without parameters), the compiler no longer
provides the default constructor
• Defining a parameterized constructor does not automatically create a no-argument
constructor, we must explicitly define if needed
• The default constructor can be implicit or explicit.
DEFAULT CONSTRUCTOR
❑ Implicit Default Constructor: If no constructor is defined in a class, the Java
compiler automatically provides a default constructor. This constructor doesn’t take
any parameters and initializes the object with default values, such as 0 for numbers,
null for objects.

❑ Explicit Default Constructor: If we define a constructor that takes no parameters,


it's called an explicit default constructor. This constructor replaces the one the
compiler would normally create automatically. Once you define any constructor
(with or without parameters), the compiler no longer provides the default constructor
for you.
DEFAULT CONSTRUCTOR
// Java Program to demonstrateDefault Constructor
import java.io.*; // Driver class
class Test{

// Default Constructor
Test() {
System.out.println("Default constructor");

// Driver function
public static void main(String[] args)
{
Test dc = new Test();
}
}
PARAMETERIZED CONSTRUCTOR
2. Parameterized import java.io.*;
Constructor class Test {
• A constructor that // data members of the class
has parameters is String name;
known as int id;
parameterized Test (String name, int id)
constructor {
• If we want to this.name = name;
initialize fields of the this.id = id;
class with our own }
values, then use a }
parameterized
constructor.
PARAMETERIZED CONSTRUCTOR

class PC
{
public static void main(String[] args)
{
// This would invoke the parameterized constructor
PC cons = new PC("Sweta", 68);
System.out.println("Name: " + cons.name + " and Id: " + cons.id);
}
}
COPY CONSTRUCTOR
3. Copy Constructor import java.io.*;
• Copy constructor is class Test {
passed with another object String name;
which copies the data int id;
available from the passed // Parameterized Constructor
object to the newly Test (String name, int id)
created object. {
• Java does not provide a this.name = name;
built-in copy constructor this.id = id;
like C++ }
• Can create our own by // Copy Constructor
writing a constructor that Test (Test obj2)
takes an object of the {
same class as a parameter this.name = obj2.name;
and copies its fields this.id = obj2.id;
}
}
COPY CONSTRUCTOR

class CopyC {
public static void main(String[] args)
{
// This would invoke the parameterized constructor
System.out.println("First Object");
Test t1 = new Test("Sweta", 68);
System.out.println(“Name: " + t1.name + " and Id: " + t1.id);
System.out.println();

// This would invoke the copy constructor


Test t2 = new Test(t1);
System.out.println(
"Copy Constructor used Second Object");
System.out.println("Name: " + t2.name + " and Id: " + t2.id);
}
}
CONSTRUCTOR OVERLOADING
import java.io.*;
• Allows to create
class Test{
multiple constructors in // constructor with one argument
the same class with Test(String name){
different parameter lists System.out.println("Constructor with one "
• Example demonstrates + "argument - String: " + name);}
constructor // constructor with two arguments
overloading, where Test (String name, int age){
multiple constructors System.out.println(
perform the same task "Constructor with two arguments: "
+ " String and Integer: " + name + " " + age);
(initializing an object)
}
with different types or // Constructor with one argument but with different
numbers of arguments. // type than previous
Test(long id)
{
System.out.println( "Constructor with one argument:
“ + "Long: " + id);
}
}
CONSTRUCTOR OVERLOADING

class Consover {
public static void main(String[] args)
{
// Invoke the constructor with one argument of
// type 'String'.
Test t2 = new Test("Sweta");

// Invoke the constructor with two arguments


Test t3 = new Test("Amiya", 28);

// Invoke the constructor with one argument of


// type 'Long'.
Test t4 = new Test(325614567);
}
}
EXERCISE
1. Write a Java program to create a class called "Cat" with instance variables name and
age. Implement a default constructor that initializes the name to "Unknown" and the
age to 0. Print the values of the variables. (Default constructor)

2. Write a Java program to create a class called Dog with instance variables name and
color. Implement a parameterized constructor that takes name and color as
parameters and initializes the instance variables. Print the values of the variables.
(Parameterized constructor)

3. Write a Java program to create a class called "Book" with instance variables title,
author, and price. Implement a default constructor and two parameterized
constructors: (Constructor overloading)
One constructor takes title and author as parameters.
The other constructor takes title, author, and price as parameters.
Print the values of the variables for each constructor.
EXERCISE

4. Write a Java program to create a class called Rectangle with instance variables
length and width. Implement a parameterized constructor and a copy constructor that
initializes a new object using the values of an existing object. Print the values of the
variables. (Copy constructor)
this KEYWORD
• "this" is a reference variable that refers to the current object, or can be said "this" in
Java is a keyword that refers to the current object instance
• It is mainly used to:
✓ Call current class methods and fields
✓ To pass an instance of the current class as a parameter
✓ To differentiate between the local and instance variables
▪ this keyword can be used to access instance variables and methods of the object on
which the method or constructor is being invoked
• In the example discussed a "Person" class is defined with two private fields "name"
and "age"
• Person class constructor is defined to initialize these fields using "this" keyword
• methods are defined for these fields which use this keyword to refer to the current
object instance
• In the printDetails() method, "this" keyword refers to the current object instance and
print its name, age, and object reference.
• In the Main class, two Person objects are created and called the printDetails()
method on each object
• The output shows the name, age, and object reference of each object instance
public void printDetails()
public class Person { {
String name; System.out.println("Name: " + this.name);
int age; System.out.println("Age: " + this.age);
Person(String name, int age) System.out.println();
{ }
this.name = name; public static void main(String[] args)
this.age = age; {
} Person first = new Person(“Anil", 18);
public String get_name() { Person second = new Person(“Rita", 22);
return name; first.printDetails();
} second.printDetails();
public void change_name(String first.change_name(“Manoj");
name) System.out.println("Name has been changed
{ to: "+ first.get_name());
this.name = name; }
} }

You might also like