Unit 2
Unit 2
Simula
Smalltalk
Java, C#, PHP, Python, C++, etc.
Object-Oriented Programming Concepts:
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
Difference between Object-based and object-oriented programming
language
How to create class
• Syntax to declare a class:
class <class_name>{
field;
method;
}
Instance variable in Java
Method in Java
new keyword in Java
Example of class
1. class Student{
2. int id;
3. String name;
4. }
5. class TestStudent1{
6. public static void main(String args[]){
7. Student s1=new Student();
8. System.out.println(s1.id);
9. System.out.println(s1.name);
10. } }
3-Ways to initialize object
1. class Student{
2. int id;
3. String name;
4. }
5. class TestStudent2{
6. public static void main(String args[]){
7. Student s1=new Student();
8. s1.id=101;
9. s1.name=“XYZ";
10. System.out.println(s1.id+" "+s1.name);//printing members with a white s
pace }
11.}
Object and Class Example: Initialization through method
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();
} }
Constructor
• In Java, a constructor is a block of codes similar to the method. It is called
when an instance of the class is created. At the time of calling constructor,
memory for the object is allocated in the memory.
• It is a special type of method which is used to initialize the object.
• Every time an object is created using the new() keyword, at least one
constructor is called.
• It calls a default constructor if there is no constructor available in the class.
In such case, Java compiler provides a default constructor by default.
• Rules for creating Java constructor
• There are two rules defined for the constructor.
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized
• Teypes of Java constructors
• There are two types of constructors in Java:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
Example of default constructor
class Bike1{
//creating a default constructor
Bike1()
{
System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Java Parameterized Constructor
//Java Program to demonstrate the use of the parameterized constructor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
Constructor Overloading in Java
2. id = i;
3. name = n;
4. age=a; }
9. s1.display();
10. s2.display();
11. } }
this Keyword
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: to refer current class instance variable
• The this keyword can be used to refer current class instance
variable. If there is ambiguity between the instance variables and
parameters, this keyword resolves the problem of ambiguity.
For example
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
1.class TestThis1{
2.public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Example with this keyword
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Inheritance in Java
• 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. When you inherit
from an existing class, you can reuse methods and fields of the
parent class. Moreover, you can add new methods and fields in your
current class also.
• Inheritance represents the IS-A relationship which is also known as
a parent-child relationship.
Why use inheritance in java
• For Method Overriding (so runtime polymorphism can be
achieved).
• For Code Reusability.
The syntax of Java Inheritance
1.class Subclass-name extends Superclass-name
2.{
3. //methods and fields
4.}
Example
1.class Employee{
2. float salary=40000;
3.}
4.class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10.}
11.}
Types of inheritance in java
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();
}}
Multilevel Inheritance Example
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();
}}
Hierarchical Inheritance Example
1.class Animal{
2.void eat(){System.out.println("eating...");}
3.}
4.class Dog extends Animal{
5.void bark(){System.out.println("barking...");}
6.}
7.class Cat extends Animal{
8.void meow(){System.out.println("meowing...");}
9.}
10.class TestInheritance3{
11.public static void main(String args[]){
12.Cat c=new Cat();
13.c.meow();
14.c.eat();
15.//c.bark();//C.T.Error
16.}}
Why multiple inheritance is not supported in java?
• To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.
• Consider a scenario where A, B, and C are three classes. The C class inherits A
and B classes. If A and B classes have the same method and you call it from child
class object, there will be ambiguity to call the method of A or B class.
• Since compile-time errors are better than runtime errors, Java renders compile-
time error if you inherit 2 classes. So whether you have same method or different,
there will be compile time error.
Use of Final
class A {
final void meth() {
System.out.println("This is a final method.");
}}
class B extends A {
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}}
Using final to Prevent Inheritance
Sometimes you will want to prevent a class from being inherited. To
do this, precede the class declaration with final. Declaring a class as
final implicitly declares all of its methods as final, too. As you might
expect, 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 implementation.
final class A {
// ... }
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ... }
Using Abstract Classes
8/29/2024 3
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.
class Factorial {
// this is a recursive function
int fact(int n) {
int result;
if(n==1) return 1;
result = fact(n-1) * n;
return result;
}}
8/29/2024 4
Contd…
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}
8/29/2024
Method overriding
• You can override any method of the base class
by declaring the method in your subclass with
the same signature (same return type, method
name, and parameter list)
• If you have overridden a base class method
and wish to access the base class version of it,
you can again use the super keyword
8/29/2024 6
Overriding example
class A
{ public void sum()
{
System.out.println("this is the sum of A");
}
}
class B extends A
{
} }
8/29/2024 7
Super keyword
• If your method overrides one of its superclass's
methods, you can invoke the overridden method
through the use of the keyword super. You can also
use super to refer to a hidden field.
class A
{ public void sum()
{
System.out.println("this is the sum of A");
}
}
8/29/2024 8
Contd…
class B extends A
{
} }
8/29/2024 9
Dynamic Method dispatch
• Dynamic method dispatch is the mechanism by which a call to an
overridden method is resolved at run time, rather than compile
time. Dynamic method dispatch is important because this is how
Java implements run-time polymorphism.
8/29/2024 13
Using Command-Line Arguments
• Sometimes you will want to pass information into a program
when you run it. This is accomplished by passing command-line
arguments to main( ). A command-line argument is the
information that directly follows the program’s name on the
command line when it is executed. To access the command-line
arguments inside a Java program is quite easy—they are stored
as strings in the String array passed to main( )
8/29/2024 14
// Display all command-line arguments.
class CommandLine {
public static void main(String args[]) {
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " +
args[i]);
}
}
8/29/2024 15
This Keyword
• Sometimes a method will need to refer to the
object that invoked it. To allow this, Java
defines the this keyword.
• this can be used inside any method to refer
to the current object. That is, this is always a
reference to the object on which the method
was invoked.
• You can use this anywhere a reference to an
object of the current class’ type is permitted.
8/29/2024 16
Box(double w, double h, double d)
{
this.width = w;
this.height = h;
this.depth = d;
}
8/29/2024 17
Garbage Collection in java
• Since objects are dynamically allocated by using the new
operator, you might be wondering how such objects are
destroyed and their memory released for later
reallocation.
• In some languages, such as C++, dynamically allocated
objects must be manually released by use of a delete
operator. Java takes a different approach.
• It handles deallocation for you automatically. The
technique that accomplishes this is called garbage
collection.
• It works like this: 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.
18
Finalize() Method
• Sometimes an object will need to perform
some action when it is destroyed. For
example, if an object is holding some non-Java
resource such as a file handle or window
character font, then you might want to make
sure these resources are freed before an
object is destroyed. To handle such situations,
Java provides a mechanism called finalization.
By using finalization, you can define specific
actions that will occur when an object is just
about to be reclaimed by the garbage
collector.
8/29/2024 19
Syntax of finalize() method
protected void finalize( )
{
// finalization code here
}
8/29/2024 20
Static keyword in java
The static keyword in Java is used for memory management
mainly.
We can apply static keyword with variables, methods, blocks
and nested classes. The static keyword belongs to the class
than an instance of the class.
The static can be:
1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block
4. Nested class
Java static variable
String college="ITS";
String name;
Student(int r, String n)
{ rollno = r; name = n; }
s1.display(); s2.display();
} }
Output:
111 Karan ITS
222 Aryan ITS
Program of the counter without static variable
//Java Program to demonstrate the use of an instance variable
//which get memory each time when we create an object of the class.
class Counter{
int count=0;//will get memory each time when the instance is created
Counter(){
count++;//incrementing value
System.out.println(count);
}
public static void main(String args[]){ //Creating objects
Counter c1=new Counter(); Counter c2=new Counter();
Counter c3=new Counter(); }
}
• In the above example, we have created an instance variable
named count which is incremented in the constructor. Since
instance variable gets the memory at the time of object
creation, each object will have the copy of the instance
variable. If it is incremented, it won't reflect other objects.
So each object will have the value 1 in the count variable.
Program of counter by static variable
As we have mentioned above, static variable will get the memory only once, if any object
changes the value of the static variable, it will retain its value.
//Java Program to illustrate the use of static variable which is shared with all
objects.
class Counter2{
static int count=0;//will get memory only once and retain its value
Counter2(){
count++;//incrementing the value of static variable
System.out.println(count);
}
public static void main(String args[]){
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2(); }
}
Java static method
The access 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 many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient,
etc. Here, we are going to learn the access modifiers only.
Interface in Java
• Java does not support multiple inheritance as
C++ supports
• Java supports an alternative approach to this
OOP feature known as interface
• What is Interface?
– An interface is basically a kind of class. Like
classes, an interface contains members and
methods; unlike classes, in interface all members
are final and all methods are abstract
• Syntax
area1=cir;
System.out.println(“ Area of circle=“
+area1.compute(10,0));
}
}
Implementing Multiple interface
Class student
{
int rollno;
void getnumber (int n)
{
rollno = n;
} void putnumber()
{
System.out.println(“rollno” +rollno);
}}
Class Test extends student
{ float part1, part2;
Void getmarks ( float m1, float m2)
{
part1=m1;
part2=m2;
}
Void putmarks()
{
System.out.println(“part1” +part11);
System.out.println(“part2” +part2);
} }
interface sports
{
Float sportwt= 6.0;
Void putwt();
}
Class results extends test implements sports
{
Float total;
Public void putwt()
{
System.out.println(“sports wt” +sportwt);
}
Void display()
{
total= part1+part2+sportwt;
putnumber( );
Putmarks( );
Putwt( );
System.out.println(“total score” +total);
} }
class hybride
{ public static void main(String args[])
{ results R1= new results();
R1.getnumber(1280)
R1.getmarks(27.0, 33.5);
R1.display();
} }