Uploaded by kjavvadi255

OOP Through Java - UNIT-2

advertisement
Unit 2: Classes, Inheritance, Polymorphism, Abstraction
Unit-2
Class
What is a class?
A class is a group of objects that has common properties. It is a template or
blueprint from which objects are created..
A class in java can contain:
– data member
– method
– constructor
– block
– class and interface
Syntax to declare a class:
class <class_name>
{
data member;
method;
}
Object
An entity that have state and behavior is called as object.
Ex: Chair, TV, table pent
Characteristic of Object:
– State : represents the data of an object. (value)
– Behavior : represents the behavior of an object (Functionality)
– Identity: Object identity is typically implemented via a unique ID. The value of the ID is
not visible to the external user, but is used internally by the JVM to identify each object
uniquely.
Example: pen is an object name is Reynolds color is white etc., known as state. Used for writing
is its behavior.
Object is instance of the class. Class is a template or blueprint from which objects are created.
Syntax of class:
class classname
{
type instance-variable1;
type instance-variable2;
//....
type instance-variableN;
type methodname1(parameter-list)
{
// body of method
}
type methodname2(parameter-list)
{
VITB, CSE Department, II CSE I SEM
Page 1
Unit 2: Classes, Inheritance, Polymorphism, Abstraction
// body of method
}
// ...
type methodnameN(parameter-list)
{
// body of method
}
}
Program
public class MyPoint
{
int x = 0;
int y = 0;
void displayPoint()
{
System.out.println("Printing the coordinates");
System.out.println(x + " " + y);
}
public static void main(String args[])
{
MyPoint obj; // declaration
obj = new MyPoint(); // allocation of memory to an object
obj.x=10; //access data member using object.
obj.y=20;
obj.displayPoint(); // calling a member method
}
}
Anonymous Object
Anonymous means nameless. An object that have no reference is known as anonymous object. If
you want to use the object only once, anonymous object is a good approach.
Program
class Calculation
{
void fact(int n)
{
int fact=1;
for(int i=1;i<=n;i++)
{
fact=fact*i;
}
VITB, CSE Department, II CSE I SEM
Page 2
Unit 2: Classes, Inheritance, Polymorphism, Abstraction
System.out.println("factorial is"+fact);
}
public static void main(String args[])
{
new Calculation().fact(5);
}
}
•
•
•
Method Overloading
Class have multiple methods by same name but different parameter, it is know as Method
Overloading.
Advantage of method overloading
– It increases the readability of the program.
Different ways to overload the method:
– By Changing number of arguments
– By changing the data type
Program1
class Calculation1
{
void sum(int a, int b)
{
System.out.println(a+b);
}
void sum(int a, int b, int c)
{
System.out.println(a+b+c);
}
public static void main(String args[])
{
Calculation1 obj=new Calculation1();
obj.sum(10,10,10);
obj.sum(20,20);
}
}
Program2
class Calculation2
{
void sum(int a, int b)
{
System.out.println(a+b);
}
void sum(double a, double b)
{
System.out.println(a+b);
VITB, CSE Department, II CSE I SEM
Page 3
Unit 2: Classes, Inheritance, Polymorphism, Abstraction
}
public static void main(String args[])
{
Calculation2 obj=new Calculation2();
obj.sum(10.5,10.5);
obj.sum(20,20);
}
}
•
•
•
•
•
Constructor
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides
data for the object that is why it is known as constructor.
Rules for creating java constructor
– There are basically two rules defined for the constructor.
– Constructor name must be same as its class name
– Constructor must have no explicit return type
Default Constructor
A constructor that have no parameter is known as default constructor.
Purpose:
– Default constructor provides the default values to the object like 0, null etc. depending on
the type.
Syntax of default constructor: <class_name>(){}
Program
class Point1
{
int x;
int y;
Point1() //constructor of class
{
x = 10;
y = 20;
}
void display()
{
System.out.println("\n\n\t-----Printing the coordinates-----");
VITB, CSE Department, II CSE I SEM
Page 4
Unit 2: Classes, Inheritance, Polymorphism, Abstraction
System.out.println("\t\t\t" + x + " " + y);
}
}
class pointDemo
{
public static void main(String args[])
{
Point1 p1 = new Point1(); // constructor will be call automatically from here
p1.display();
}
}
•
•
Parameterized Constructor
A constructor that have parameters is known as parameterized constructor.
Purpose:
– Parameterized constructor provides the values at runtime when the object is created
depending on the type.
Syntax of default constructor: <class_name>(datatype parameter1,….){}
Program
import java.util.Scanner;
class Point2
{
int x;
int y;
Point2(int a, int b)
{
x = a;
y = b;
}
void display()
{
System.out.println("\n\n\t-----Printing the coordinates-----");
System.out.println("\t\t\t" + x + " " + y);
}
}
class pointDemo1
{
public static void main(String args[])
{
int i,k;
Scanner s = new Scanner(System.in);
System.out.print("Enter int value for i : ");
i = s.nextInt();
System.out.print("Enter int value for k : ");
k = s.nextInt();
VITB, CSE Department, II CSE I SEM
Page 5
Unit 2: Classes, Inheritance, Polymorphism, Abstraction
Point2 p1 = new Point2(i,k);
p1.display();
}
}
•
Constructor Overloading
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.
Program
class Student5{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
•
•
Copy Constructor
There is no copy constructor in java. But, we can copy the values of one object to another like
copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
– By constructor
– By assigning the values of one object into another
– By clone() method of Object class
VITB, CSE Department, II CSE I SEM
Page 6
Unit 2: Classes, Inheritance, Polymorphism, Abstraction
Constructor Vs Method
Static Keyword
•
•
•
•
•
•
The static keyword is used in java mainly for memory management.
Static keyword applied with Variables, methods and blocks. Static keyword belongs to the class
than instance of the class..
The static variable can be used to refer the common property of all object(it is not unique for each
object).
Static variable gets memory only once in class area at the time of class loading.
Advantage of Static variable
It makes your program memory efficient (ie., it saves memory)
VITB, CSE Department, II CSE I SEM
Page 7
Unit 2: Classes, Inheritance, Polymorphism, Abstraction
Program on static variable
class Student
{
int rollno;
String name;
static String college="ITS";
Student(int r, String n)
{
rollno = r;
name = n;
}
void display()
{
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[])
{
Student s1 = new Student(111,"Abinav");
Student s2 = new Student(222,"Harshitha");
s1.display();
s2.display();
}
}
Static Method
•
•
•
A static method belongs to the class rather than object of a class.
A static method can be invoked without the need for creating an instance of a class.
Static method can access static data member and can change the value of it.
Program
class Student1
{
int rollno;
String name;
static String college=“VITB";
static void change()
{
college = “VIT";
}
Student1(int r, String n)
{
rollno = r;
name = n;
}
VITB, CSE Department, II CSE I SEM
Page 8
Unit 2: Classes, Inheritance, Polymorphism, Abstraction
void display()
{
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[])
{
Student1.change();
Student1 s1 = new Student1(111,"Abinav");
Student1 s2 = new Student1(222,"Harshitha");
Student1 s3 = new Student1(333,"Aadharsh");
}
}
s1.display();
s2.display();
s3.display();
Static Block
Is used to initialize the static data member.
It is executed before main method at the time of classloading
This Keyword
•
•
In java, this is a reference variable that refers to the current object.
Usage of java this keyword (6 usage of java this keyword)
– this keyword can be used to refer current class instance variable.
– this() can be used to invoke current class constructor.
– this keyword can be used to invoke current class method (implicitly)
– this can be passed as an argument in the method call.
– this can be passed as argument in the constructor call.
– this keyword can also be used to return the current class instance.
Program1
class student12
{
int id;
String name;
student2(int id, String name)
{
this.id = id;
this.name = name;
}
void display()
{
System.out.println(id+" "+name);
}
VITB, CSE Department, II CSE I SEM
Page 9
Unit 2: Classes, Inheritance, Polymorphism, Abstraction
public static void main(String args[])
{
student12 s1 = new student12(111, "raaki");
student12 s2 = new student12(444, "Arvind");
s1.display();
s2.display();
}
}
Program2
class Student13{
int id;
String name;
Student13(){System.out.println("default constructor is invoked");}
Student13(int id,String name){
this ();//it is used to invoked current class constructor.
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
}
public static void main(String args[]){
Student13 e1 = new Student13(111,"kiran");
Student13 e2 = new Student13(222,"Aryan");
e1.display();
e2.display();
}
Program3
class S{
void m(){
System.out.println("method is invoked");
}
void n(){
this.m();//no need because compiler does it for you.
}
void p(){
n();//complier will add this to invoke n() method as this.n()
}
public static void main(String args[]){
S s1 = new S();
s1.p();
}
VITB, CSE Department, II CSE I SEM
Page 10
Unit 2: Classes, Inheritance, Polymorphism, Abstraction
}
Program4
class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}
Program5
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
VITB, CSE Department, II CSE I SEM
Page 11
Unit 2: Classes, Inheritance, Polymorphism, Abstraction
Program6
class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello java");}
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
Inheritance
•
•
•
•
•
•
•
•
•
•
Inheritance is a mechanism in which one object acquires all the properties and behavior of another
object.
Inheritance represents the IS-A relationship, also known as parent-child relationship.
Why use inheritance in java
– For Method Overriding (so runtime polymorphism can be achieved).
– For Code Reusability.
Syntax of Java Inheritance
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.
In the terminology of Java, a class that is inherited is called a super class. The new class is called a
subclass.
Types of Inheritance
•
Three types of inheritance in java: single, multilevel and hierarchical.
VITB, CSE Department, II CSE I SEM
Page 12
Unit 2: Classes, Inheritance, Polymorphism, Abstraction
Note: multiple and hybrid inheritance is supported through interface
Program on single Inheritance
class Employee
{
int salary=40000;
}
class Programmer extends Employee
{
int bonus = 10000;
public static void main(String args[])
{
Programmer p = new Programmer();
System.out.println("Programmer Salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Program on multilevel inheritance
Class X
{
public void methodX()
{
System.out.println("Class X method");
}
}
Class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}
}
Class Z extends Y
{
public void methodZ()
{
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grand parent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
}
VITB, CSE Department, II CSE I SEM
Page 13
Unit 2: Classes, Inheritance, Polymorphism, Abstraction
}
Program on Hierarchial Inheritance
Class A
{
public void methodA()
{
System.out.println("method of Class A");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
Class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
Class D extends A
{
public void methodD()
{
System.out.println("method of Class D");
}
}
Class MyClass
{
public void methodB()
{
System.out.println("method of Class B");
}
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
obj1.methodA();
obj2.methodA();
obj3.methodA();
}
}
VITB, CSE Department, II CSE I SEM
Page 14
Unit 2: Classes, Inheritance, Polymorphism, Abstraction
Method Overriding
•
•
Having the same name in the subclass as declared in the parent class is known as method
overriding.
If a subclass provides a specific implementation of a method that is already provided by its super
class, it is know as Method Overriding.
Advantages of Method Overriding
•
•
•
Method overriding is used to provide specific implementation of a method of a method that is
already provided by its super class.
Method overriding is used for Runtime Polymorphism.
Rules for Method Overriding:
– Method must have same name as in the parent class.
– Method must have same parameter as in parent class.
Program
class Vehicle
{
void run()
{
System.out.println("Vehicle is running");
}
}
class Bike1 extends Vehicle
{
void run()
{
System.out.println("Bike is running Safely");
}
public static void main(String args[])
{
Bike1 obj = new Bike1();
obj.run();
}
}
Super Keyword
•
•
Super is a reference variable that is used to refer immediate parent class object.
Uses of super keyword
– super is used to refer immediate parent class instance variable.
– super() is used to invoke immediate parent class constructor.
– Super is used to invoke immediate parent class method.
VITB, CSE Department, II CSE I SEM
Page 15
Unit 2: Classes, Inheritance, Polymorphism, Abstraction
Program to invoke super class variable in subclass
class Vehicle
{
int speed=50;
}
class Bike3 extends Vehicle
{
int speed = 100;
void display()
{
System.out.println(super.speed);
}
public static void main(String args[])
{
Bike3 b=new Bike3();
b.display();
}
}
Program to invoke super class method in subclass
class Person{
void message(){System.out.println("welcome");}
}
class Student16 extends Person{
void message(){System.out.println("welcome to java");}
void display(){
message();//will invoke current class message() method
super.message();//will invoke parent class message() method
}
public static void main(String args[]){
Student16 s=new Student16();
s.display();
}
}
Program to invoke super class constructor in subclass
class Vehicle
{
Vehicle()
{
System.out.println("Vehicle is created");
}
VITB, CSE Department, II CSE I SEM
Page 16
Unit 2: Classes, Inheritance, Polymorphism, Abstraction
}
class Bike5 extends Vehicle
{
Bike5()
{
super();
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike5 b=new Bike5();
}
}
Final Keyword
• The final keyword in java is used to restrict the user.
• The final keyword can be used in many context. Final can be:
– variable,
– method
– Class
• The final keyword can be applied with the variables, that have no value it is called blank final
variable.
• It can be initialized in the constructor only.
• The blank final variable can be static also which will be initialized in the static block only.
Final Variable
• If you make any variable as final, you cannot change the value of the final variable(it will be
constant).
Program
class Bike5
{
final int speedlimit=90;
void run()
{
speedlimit=400;
}
public static void main(String args[])
{
Bike5 obj=new Bike5();
obj.run();
}
}
Output: Compile time error
VITB, CSE Department, II CSE I SEM
Page 17
Unit 2: Classes, Inheritance, Polymorphism, Abstraction
Final Method
•
If you make any method as final you cannot override it.
Program
class Bike6
{
final void run()
{
System.out.println("running");
}
}
class suziki extends Bike6
{
void run()
{
System.out.println("running safetly");
}
public static void main(String args[])
{
suziki obj1=new suziki();
suziki.run();
}
}
Output: Compiletime error
Final Class
• If you make any class as final, you cannot extend it.
Program
final class Bike7
{}
class Honda extends Bike7
{
void run()
{
System.out.println("running safetly");
}
public static void main(String args[])
{
Honda honda = new Honda();
honda.run();
}
VITB, CSE Department, II CSE I SEM
Page 18
Unit 2: Classes, Inheritance, Polymorphism, Abstraction
}
Polymorphism
•
•
•
An object of a sub class can be used whenever its super class object is required . This is known as
polymorphism.
In simple terms polymorphism means that a variable of super type can refer to a sub type object.
There are two types of polymorphism :
– Compile-time polymorphism
– Runtime Polymorphism
Polymorphism allows one interface to be used for a set of actions i.e. one name may refer to
different functionality.
Polymorphism allows a object to accept different requests of a client and responds according to the current
state of the runtime system, all without bothering the user.
•
VITB, CSE Department, II CSE I SEM
Page 19
Unit 2: Classes, Inheritance, Polymorphism, Abstraction
Compile-time polymorphism
•
•
In compile-time Polymorphism, method to be invoked is determined at the compile time. Compile
time polymorphism is supported through the method overloading concept in java.
Method overloading means having multiple methods with same name but with different signature
(number, type and order of parameters).
Program
class A{
public void fun1(int x){
System.out.println("The value of class A is : " + x);
}
public void fun1(int x,int y){
System.out.println("The value of class B is : " + x + " and " + y);
}
}
public class polyone{
public static void main(String[] args){
A obj=new A();
obj.fun1(2);
obj.fun1(2,3);
}
}
Runtime Polymorphism
•
In rumtime polymorphism, the method to be invoked is determined at the run time. The example of
run time polymorphism is method overriding. When a subclass contains a method with the same
name and signature as in the super class then it is called as method overriding.
Program
class A{
public void fun1(int x){
System.out.println("int in Class A is : "+ x);
}
}
class B extends A{
public void fun1(int x){
System.out.println("int in Class B is : "+ x);
}
}
public class polytwo{
public static void main(String[] args){
A obj;
obj= new A(); // line 1
VITB, CSE Department, II CSE I SEM
Page 20
Unit 2: Classes, Inheritance, Polymorphism, Abstraction
obj.fun1(2); // line 2 (prints "int in Class A is : 2")
}
obj=new B(); // line 3
obj.fun1(5); // line 4 (prints ""int in Class B is : 5")
}
Abstraction in Java
Abstract Class
A class that is declared with abstract keyword, is known as abstract class in java. It can have
abstract and non-abstract methods.
– It needs to be extended and its method implemented. It cannot be instantiated.
– Ex: abstract class A{}
Ways to achieve Abstaction
– There are two ways to achieve abstraction in java
– Abstract class (0 to 100%)
– Interface (100%)
–
•
abstract method
– A method that is declared as abstract and does not have implementation is known as
abstract method.
Ex: abstract void printStatus();//no body and abstract
•
Program1
abstract class Bike
{
abstract void run();
}
class Hero extends Bike
{
void run()
{
System.out.println("running safetly...");
}
public static void main(String args[])
{
Hero obj = new Hero();
obj.run();
}
}
VITB, CSE Department, II CSE I SEM
Page 21
Unit 2: Classes, Inheritance, Polymorphism, Abstraction
Program2
abstract class Bike
{
abstract void run();
void changeGear()
{
System.out.println("gear changed");
}
}
class Hero1 extends Bike
{
void run()
{
System.out.println("running safetly...");
}
class TestAbstraction2{
public static void main(String args[])
{
Bike obj = new Hero1();
obj.run();
obj.changeGear();
}
}
Program3
abstract class motorBike
{
int limit=30;
motorBike()
{
System.out.println("constructor is invoked");
}
void getDetails()
{
System.out.println("it has two wheels");
}
abstract void run();
}
class Mahindra extends motorBike
{
void run()
{
System.out.println("running safetly..");
}
public static void main(String args[])
{
motorBike obj = new Mahindra();
obj.run();
obj.getDetails();
System.out.println(obj.limit);
}
VITB, CSE Department, II CSE I SEM
Page 22
Unit 2: Classes, Inheritance, Polymorphism, Abstraction
}
------------------------End of 2nd Unit----------------
VITB, CSE Department, II CSE I SEM
Page 23
Download