You are on page 1of 50

Class and Objects (Contd)

Variable arguments
• Variable number of arguments in a function/method
• This feature is called varargs and it is short-form for variable-length
arguments
• A variable-length argument is specified by three periods(…)
• While defining method signature, always keep varargs at last
• A method can have only one varargs parameter
class Test2
{
// Takes string as a argument followed by varargs
static void fun2(String str, int ...a)
{
System.out.println("String: " + str);
System.out.println("Number of arguments is: "+ a.length);
}

public static void main(String args[])


{
// Calling fun2() with different parameter
fun2(“IPM", 100, 200);
fun2(“Java", 1, 2, 3, 4, 5);
fun2(“SectionA");
}
}
Vararg and ambiguity
class Demo
{
static void test(int ... vargs)
{
// method body
}

static void test(int n, int ... vargs)


{
// method body
}
}
Inheritance
• Super class
• Sub class
• ‘extends’ keyword
• Intermediate class
• Three types: Single, multilevel, hierarchical inheritance
Single Inheritance
• A structure having one and only one parent as well as child class
• Child class is authorized to access the property of Parent class
Syntax :
class A
{
……
}
class B extends A
{
….
}
Multilevel Inheritance
• Multiple level of inheritance
• Child class as well as intermediate class may access the properties of upper
level classes
Syntax :
class A
{
……
}
class B extends A
{
….
}
Class C extends B
{
….
}
Hierarchical Inheritance
• A structure having one parent and more than one child class
• Child classes must be connected with only Parent class
Syntax :
class A
{
……
}
class B extends A
{
….
}
Class C extends A
{
….
}
‘super’ keyword
• Constructor of parent class can be called from sub class using ‘super’
keyword
• To access the data members of parent class when both parent and
child class have member with same name
• To access the method of parent class when child class has overridden
that method
Example: ‘super’ keyword
class Animal
{
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor()
{
System.out.println(color);
System.out.println(super.color);
}
}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
d.printColor();
}}
Example: ‘super’ keyword
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
Example: ‘super’ keyword
class Animal
{
Animal()
{
System.out.println("animal is created");
}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
Method overriding
• If subclass (child class) has the same method as declared in the parent
class, it is known as method overriding in Java
• Rules:
• The method must have the same name as in the parent class
• The method must have the same parameter as in the parent class
class Vehicle
{
void run()
{
System.out.println("Vehicle is running");}
}
class Bike2 extends Vehicle
{
void run()
{
System.out.println("Bike is running safely");
}
public static void main(String args[]){
Bike2 obj = new Bike2();
obj.run();
}
}
Real-Life Application of Method Overriding
• Examples?
class Bank{
int getRateOfInterest() {return 0;}
}
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}

class ICICI extends Bank{


int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
Static Method and Overriding
• A static method cannot be overridden
• It is because the static method is bound with class whereas instance
method is bound with an object
• For the same reason, main method in java cannot be overridden
Method Overriding and Dynamic Method Dispatch
• Method Overriding is an example of runtime polymorphism
• The call to the overridden method is determined at runtime, because
during method call which method(parent class or child class) is to be
executed is determined by the type of object
• This process in which call to the overridden method is resolved at
runtime is known as dynamic method dispatch
Method overriding and access modifiers
• Access Modifier of the overriding method (method of subclass)
cannot be more restrictive than the overridden method of parent
class
• For e.g. if the Access Modifier of parent class method is public then
the overriding method (child class method ) cannot have private and
protected, because both of these three access modifiers are more
restrictive than public
Output
class MyBaseClass{
public void disp()
{
System.out.println("Parent class method");
}
}
class MyChildClass extends MyBaseClass{
protected void disp(){
System.out.println("Child class method");
}
public static void main( String args[]) {
MyChildClass obj = new MyChildClass();
obj.disp();
}
}
When are constructors executed?
Key Concepts of Object Oriented Programming
1) Class and Object
2) Inheritance
3) Polymorphism
4) Abstraction
5) Encapsulation
Class and Object
• Class represents the set of properties or methods that are common to
all objects of one type.
• An object can be defined as an instance of a class
• Class is only a logical component and object is the physical entity
Inheritance
• Inheritance is an Object Oriented Programming concept in which one
object acquires the properties and behaviors of the parent object
• It’s creating a parent-child relationship between two classes
• Super class-sub class using ‘extends’ keyword
Polymorphism
• Polymorphism is the ability of an object to take on many forms
• Two types:
• 1) Static Polymorphism also known as compile time polymorphism
2) Dynamic Polymorphism also known as runtime polymorphism

• Method overloading is an example of static polymorphism or


compile-time polymorphism
• Method overriding is an example of dynamic polymorphism or run-
time polymorphism
Encapsulation
• The wrapping the data (variables) and code acting on data (methods)
in a single unit is called encapsulation
• It is also known as data-hiding
• Encapsulation can be achieved by: Declaring all the variables in the
class as private and writing public methods in the class to set and get
the values of variables.
class EncapsulationDemo
{
private int num=112345;
public int getEmpno()
{
return num;
}
}
public class EncapsTest
{
public static void main(String args[])
{
EncapsulationDemo obj = new EncapsulationDemo();
System.out.println("Employee Number: " + obj.getEmpno());
}
}
Abstraction
• An abstraction is an act of representing essential features without
including complete details
• Abstraction can be achieved by ‘abstract’ keyword in methods and
classes
• Abstraction can also be achieved by interfaces in Java
Abstract classes
• A class which is declared with the abstract keyword is known as an
abstract class in Java
• It can have abstract and non-abstract methods (method with the
body)
• Abstraction is a process of hiding the implementation details and
showing only functionality to the user
• We can't have object of the abstract classes
• If you inherit an abstract class, you have to provide implementations
to all the abstract methods in it
abstract class Bank{
abstract int getRateOfInterest(); // Abstract-Method: See No curly-braces, only semi-colon
}
class SBI extends Bank{
int getRateOfInterest(){return 7;}
}
class PNB extends Bank{
int getRateOfInterest(){return 8;}
}

class TestBank{
public static void main(String args[]){
SBI b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
PNB c=new PNB();
System.out.println("Rate of Interest is: "+c.getRateOfInterest()+" %");
}}
‘final’ keyword
• Final is a keyword in Java that is used to restrict the user and can be
used in many respects. Final can be used with:
• Class
• Methods
• Variables
• When a class is declared as final, it cannot be extended further
• A method declared as final cannot be overridden
• Once a variable is assigned with the keyword final, it always contains
the same exact value
‘final’ keyword
• final prevents overriding
• final prevents inheritance
Output?

class Bike{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike obj=new Bike();
obj.run();
}
}
Output

class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}
Output
final class Bike{}

class Honda1 extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}
Output
class Bike11{
int cube(final int n){
n=n+2;
return n*n*n;
}
public static void main(String args[]){
Bike11 b=new Bike11();
System.out.println(b.cube(5));
}
}
Can we declare constructor as final?
• Yes
• No
Packages
• A package is a collection of related classes providing access
protection and namespace management.
• To make classes easier to find and to use
• To avoid naming conflicts
• To control access
package myPackage;
public class ClassA {
// class body
}
class ClassB {
// class body
}
Packages
• The first line of your source file:
package <package_name>;
e.g. package cars_info;
class Car
{…}
• Every class must belong to one package.
• Only one package statement is allowed per source file.
• If package statement is omitted, the class belongs to a special default
package – the only package in Java that has no name.
Package and Access Modifier
Private Default Protected Public
Same Class Yes Yes Yes Yes
Subclass in the No Yes Yes Yes
package
Non- subclass in the No Yes Yes Yes
package
Subclass in another No No Yes Yes
package
Non-subclass in No No No Yes
another package
Assessing Classes from Packages
• Two ways:
• Using fully qualified class name
• myPackage.ClassA a=new myPackage.ClassA();

• Import package and use class name directly.


• Import package_name.*;
Packages and Name Clashing
 When packages are developed by different teams, it is possible that multiple
packages will have classes with the same name, leading to name classing.

package pack1; package pack2;

class Teacher class Teacher

class Student class Student

 We can import and use these packages like:


 import pack1.*;
 import pack2.*;
 Student student1 = new Student(); // Generates compilation error
Interface
• An interface defines a set of methods but does not implement them.
• A class that implements the interface agrees to implement all the
methods defined in the interface
• An interface is a named collection of method definitions (without
implementations).
Defining an Interface
• Defining an interface is similar to creating a new class.
• An interface definition has two components: the interface declaration and the
interface body.
interfaceDeclaration
{
interfaceBody
}
• The interfaceDeclaration declares various attributes about the interface such
as its name and whether it extends another interface.
• The interfaceBody contains the constant and method declarations within the
interface
Implementing an Interface
• Include an ‘implements’ keyword in the class declaration
• Ex: class abc extends xyz implements pqr
• A class can implement more than one interface (the Java platform
supports multiple inheritance for interfaces), so the implements
keyword is followed by a comma-separated list of the interfaces
implemented by the class
• When implement an interface, either the class must implement all
the methods declared in the interface and its superinterfaces, or the
class must be declared abstract
interface MyInterface
{
public void method1();
public void method2();
}
class Demo implements MyInterface
{
public void method1()
{
System.out.println("implementation of method1");
}
public void method2()
{
System.out.println("implementation of method2");
}
}
interface x
{
char A = ‘A’;
void firstmethod();
}
interface Y
{
char B = ‘B’;
}
interface Z extends X, Y
{
void secondmethod();
}

//What is in interface Z?
Default methods in Interface
• Default methods allows the interfaces to have methods with
implementation without affecting the classes that implement the
interface
• Preceded with the keyword ‘default’ before the method name
• Default method comes with Java 8 (also static method in interface
comes with Java 8 only)
interface TestInterface
{
public void square(int a);
default void show()
{
System.out.println("Default Method Executed");
}
}
class TestClass implements TestInterface
{
public void square(int a)
{
System.out.println(a*a);
}
public static void main(String args[])
{
TestClass d = new TestClass();
d.square(4);
d.show();
}}
interface TestInterface
{
public void square (int a);
static void show()
{
System.out.println("Static Method Executed");
}
}
class TestClass implements TestInterface
{
public void square (int a)
{
System.out.println(a*a);
}
public static void main(String args[])
{
TestClass d = new TestClass();
d.square(4);
TestInterface.show();
}

You might also like