Programming in Java Text Books :

Slides:



Advertisements
Similar presentations
INHERITANCE BASICS Reusability is achieved by INHERITANCE
Advertisements

METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
CS 2511 Fall  Abstraction Abstract class Interfaces  Encapsulation Access Specifiers Data Hiding  Inheritance  Polymorphism.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Inheritance. Introduction Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications.
JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Java programming Package. A package is a group of similar types of classes, interfaces and sub-packages. Package can be categorized in two form, built-
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.
Java Programming Final Keyword In Java. final keyword The final keyword in java is used to restrict the user. The final keyword can be used in many context.
Classes, Interfaces and Packages
CSI 3125, Preliminaries, page 1 Packages. CSI 3125, Preliminaries, page 2 Packages Packages are containers for classes Collection of classes Packages.
Java Package Advantage of Java Package
CSI 3125, Preliminaries, page 1 Inheritance. CSI 3125, Preliminaries, page 2 Inheritance Using inheritance, can create a general class that defines traits.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Java Inheritance in Java. Inheritance Inheritance is a mechanism in which one object acquires all the properties and behaviors of parent object. The idea.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
OOP Basics Classes & Methods (c) IDMS/SQL News
UNIT-2. Inheritance –Definition Single Inheritance Benefits of inheritance Member access rules super classes Polymorphism Method overriding Using final.
Methods and Classes. Method Overloading Two or more methods within the same class that share the same name but different parameters class OverloadDemo.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
Inheritance. Inheritance is a mechanism in which one object acquires all the properties and behaviors of parent object Inheritance represents the IS-A.
OOPM. Java Array Array is a collection of similar type of elements that have contiguous memory location. Java array is an object the contains elements.
Modern Programming Tools And Techniques-I
Web Design & Development Lecture 9
Programming in Java, 2e Sachin Malhotra Saurabh Choudhary.
Lecture 12 Inheritance.
Inheritance in Java Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object. The idea behind.
Inheritance-Basics.
Final and Abstract Classes
Inheritance and Polymorphism
UNIT-2.
CompSci 230 S Programming Techniques
INHERITANCE IN JAVA.
Interfaces.
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Modern Programming Tools And Techniques-I Inheritance
Inheritance Visit for more Learning Resources.
Interface.
Introduction interface in Java is a blueprint of a class. It has static constants and abstract methods only. An interface is a way to describe what classes.
Java Programming Language
Sampath Kumar S Assistant Professor, SECE
Interfaces.
Advanced Programming Behnam Hatami Fall 2017.
Sampath Kumar S Assistant Professor, SECE
Object Oriented Programming in java
Sampath Kumar S Assistant Professor, SECE
METHOD OVERRIDING in JAVA
Sampath Kumar.S Assistant Professor/IT, SECE
S.VIGNESH Assistant Professor, SECE
Inheritance Inheritance is a fundamental Object Oriented concept
Method Overriding in Java
Inheritance Cse 3rd year.
Java Programming, Second Edition
Sampath Kumar S Assistant Professor, SECE
Inheritance.
Chapter 14 Abstract Classes and Interfaces
Inheritance and Polymorphism
Chapter 11 Inheritance and Polymorphism Part 1
Final and Abstract Classes
Chapter 11 Inheritance and Encapsulation and Polymorphism
INTERFACES Explained By: Sarbjit Kaur. Lecturer, Department of Computer Application, PGG.C.G., Sector: 42, Chandigarh.
Presentation transcript:

Programming in Java Text Books : Herbert Schildt, “JAVA 2: Complete Reference”, 5th Edition, TMH Reference Books : Jim Keogh, “J2EE Complete Reference”. Kenarnold and James gosling : “The Java Programming Language”.

Inheritance, Interfaces and Packages Programming in Java Inheritance, Interfaces and Packages 1. Inheritance 2. Extending Classes, Overriding Methods 3. Final variables and Methods 4. Abstract Methods and Classes 5. Visibility control. 6. Interfaces and Packages 7. Multiple Inheritance 8. Creating and Executing Programs

Inheritance Inheritance :is a mechanism in which one object acquires all the properties and behaviors of parent object. The idea behind inheritance 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 parent class, and you can add new methods and fields also. Inheritance represents the IS-A relationship, also known as parent-child relationship. Why use inheritance…? For Method Overriding (so runtime polymorphism can be achieved). For Code Reusability.

Inheritance Inheritance Syntax The extends keyword indicates that you are making a new class that derives from an existing class. A class that is inherited is called a super class. The new class is called a subclass. class Subclass-name extends Superclass-name   {      //methods and fields   }   class Employee {    float 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);   }

class A { int i, j void showij() { System.out.println(“ i and j : “ + i + j); } } class B extends A { int k; void showk() { System.out.println(“ k : “ + k); } void sum() { System.out.println(“sum : “+(i+j+k)); class SimpleInheritance { public static void main (string[] args) { A superOb = new A(); B subOb = new B(); superOb.i = 10; superOb.j = 20; subOb.k=15; superOb.showij(); subOb.showk(); subOb.sum();

Multiple And Hybrid Inheritance Is Supported Through Interface Only Types of Inheritance Single Multiple Tree/Hierarchical Multi-level Hybrid Multiple And Hybrid Inheritance Is Supported Through Interface Only

Aggregation If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A relationship. Consider a situation, Employee object contains many informations such as id, name, emailId etc. It contains one more object named address, which contains its own informations such as city, state, country, zipcode etc. as given below. class Employee{   int id;   String name;   Address address; //Address is a class   ...   } For Code Reusability. class Address {   int Hno;   String City,State,Country; int Zipcode;   }

Aggregation class Operation { int square(int n){ return n*n; } } class Circle{ Operation op; //aggregation double pi=3.14; double area(int radius) { op=new Operation(); int rsquare= op.square(radius); //code reusability return pi*rsquare; public static void main(String args[]){ Circle c=new Circle(); double result=c.area(5); System.out.println(result);

Overriding Methods If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java. (or) If subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding. Usage of Java Method Overriding Method overriding is used to provide specific implementation of a method that is already provided by its super class. Method overriding is used for runtime polymorphism Rules for Java Method Overriding method must have same name as in the parent class method must have same parameter as in the parent class. must be IS-A relationship (inheritance).

Overriding Methods 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 time Example for overriding Methods

Real time Example for overriding Methods 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());   }   }

Abstract Class in java Example: abstract class A{} A class that is declared with abstract keyword. It can have abstract and non-abstract methods (method with body) Abstraction is a “process of hiding the implementation details and showing only functionality to the user“. There are two ways to achieve abstraction in java Abstract class (0 to 100%) Interface (100%) Example: abstract class A{} abstract method : A method that is declared as abstract and does not have implementation is known as abstract method. abstract void printStatus();

Abstract Class in java abstract class Bike{    abstract void run(); //no body and abstract    }      class Honda4 extends Bike{   void run(){ System.out.println("Running safely.."); public static void main(String args[]){   Bike obj = new Honda4();    obj.run();   Running safely….

Abstract Class in java drawing circle abstract class Shape { abstract void draw(); } class Rectangle extends Shape{ void draw() { System.out.println("drawing rectangle"); } class Circle1 extends Shape{ void draw() { System.out.println("drawing circle"); } class TestAbstraction1{ public static void main(String args[]){ Shape s=new Circle1(); s.draw(); drawing circle

Abstract Class in java Rate of Interest is: 7 % abstract class Bank{ abstract int getRateOfInterest(); } class SBI extends Bank{ int getRateOfInterest() { return 7; } class PNB extends Bank{ class TestBank{ public static void main(String args[]){ Bank b=new SBI(); //if object is PNB, method of PNB will be invoked int interest=b.getRateOfInterest(); System.out.println("Rate of Interest is: "+interest+" %"); Rate of Interest is: 7 %

Abstract class having constructor, data member, methods etc abstract class Bike { Bike() { System.out.println("bike is created"); } // Constructor abstract void run(); void changeGear() { System.out.println("gear changed"); } } class Honda extends Bike{ void run() { System.out.println("running safely.."); } class TestAbstraction2{ public static void main(String args[]) { Bike obj = new Honda(); obj.run(); obj.changeGear(); bike is created running safely.. gear changed

Java Package A java package is a group of similar types of classes, interfaces and sub-packages. Package in java can be categorized in two form, built-in package and user-defined package. There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc. Advantage of Java Package 1) Java package is used to categorize the classes and interfaces so that they can be easily maintained. 2) Java package provides access protection. 3) Java package removes naming collision.

Java Package

Java Package How to run java package program – fqn (Fully Qualified Name) e.g. mypack.Simple etc to run the class. To Compile: javac -d . Simple.java To Run: java mypack.Simple Output: Welcome to package The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . represents the current folder. How to access package from another package? There are three ways to access the package from outside the package. import package.*; import package.classname; fully qualified name.

Example of package that import the packagename.* Java Package Example of package that import the packagename.* package pack;   public class A{ public void msg() { System.out.println("Hello");}   } Javac A.java package mypack; import pack.*; class B{ public static void main(String args[]){ A obj = new A(); obj.msg(); } Javac B.java Output : Hello

Example of package that import the packagename.classname Java Package Example of package that import the packagename.classname package pack;   public class A{ public void msg() { System.out.println("Hello");}   } Javac A.java package mypack; import pack.A; class B{ public static void main(String args[]){ A obj = new A(); obj.msg(); } Javac B.java Output : Hello

Example of package that import the packagename using fqn Java Package Example of package that import the packagename using fqn package pack;   public class A{ public void msg() { System.out.println("Hello");}   } Javac A.java package mypack; import pack.A; class B{ public static void main(String args[]){ pack.A obj = new pack.A();; obj.msg(); } Javac B.java Output : Hello

Java Package Example of package HelloMoon.java HelloWorld.java package world.moon; public class HelloMoon { private String holeName = "rabbit hole"; public String getHoleName() { return holeName; } public void setHole() { this.holeName = holeName; } } HelloMoon.java pakage world; public class HelloWorld { public HelloWorld(){ System.out.println("Hello World Package"); } void getValue(){ System.out.println("The Value 5"); } } HelloWorld.java

Java Package Example of package TestPack.java import world.moon.*; public class TestPack{ public static void main(String[] args) { HelloMoon HM =new HelloMoon(); HM.setHole(); System.out.println("getHoleName = "+HM.getHoleName()); HelloWorld HW = new HelloWorld(); HW.getValue(); } TestPack.java Output: getHoleName = rabbit hole Hello World Package The Value

Access Modifiers in Java There are two types of modifiers in java access modifiers and non-access modifiers. The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or class. There are 4 types of java access modifiers: Private : accessible only within class Default : accessible only within package Protected : accessible within/outside the package but through Inheritance only Public : accessible everywhere

Access Modifiers in Java Private : accessible only within class. class A{ private A(){} private int data=40; public void msg(){ System.out.println("Hello java"); } } public class Simple{ public static void main(String args[]){ A obj=new A(); System.out.println(obj.data); obj.msg(); } . //Compile Time Error //Compile Time Error //Compile Time Error

Access Modifiers in Java The default modifier is accessible only within package. //save by A.java   package pack;   class A{   void msg() { System.out.println("Hello"); }   } //save by B.java   package mypack;   import pack.*;   class B{     public static void main(String args[]){      A obj = new A();      obj.msg();   }   } //Compile Time Error  //Compile Time Error 

Access Modifiers in Java The protected modifier is accessible outside package but through inheritance. //save by A.java   package pack; public class A{ protected void msg() { System.out.println("Hello"); } } //save by B.java   package mypack; import pack.*; class B extends A{ public static void main(String args[]){ B obj = new B(); obj.msg(); } Output : Hello

Access Modifiers in Java The public modifier is accessible anywhere. //save by A.java   package pack; public class A{ public void msg() { System.out.println("Hello"); } } //save by B.java   package mypack; import pack.*; class B{ public static void main(String args[]){ A obj = new A(); obj.msg(); } Output : Hello

Interfaces in Java It is a blueprint of a class. It has static constants and abstract methods only. There can be only abstract methods in the java interface, but not method body. It is used to achieve fully abstraction and multiple inheritance in Java. Java Interface also represents IS-A relationship. It cannot be instantiated just like abstract class. In other words, Interface fields are public, static and final bydefault, and methods are public and abstract. Why use Java interface? There are mainly three reasons to use interface. They are given below. It is used to achieve fully abstraction. By interface, we can support the functionality of multiple inheritance. It can be used to achieve loose coupling.

Interfaces in Java Interface fields are public, static and final by default, & methods are public and abstract.

Example of Interfaces in Java interface printable { void print(); } class A6 implements printable { public void print() { System.out.println("Hello"); } public static void main(String args[]) { A6 obj = new A6(); obj.print(); Output:Hello

Multiple Inheritance in Java If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as multiple inheritance.

Multiple Inheritance in Java interface Printable { void print(); } interface Showable { void show(); class A7 implements Printable,Showable { public void print() { System.out.println("Hello"); } public void show() { System.out.println("Welcome"); } public static void main(String args[]){ A7 obj = new A7(); obj.print(); obj.show(); Output:Hello Welcome

Interface Inheritance in Java interface Printable { void print(); } interface Showable extends Printable{ void show(); class Testinterface2 implements Showable{ public void print() { System.out.println("Hello"); } public void show() { System.out.println("Welcome"); } public static void main(String args[]){ Testinterface2 obj = new Testinterface2(); obj.print(); obj.show(); Hello Welcome

Points to remember for nested interfaces An interface i.e. declared within another interface or class is known as nested interface. The nested interfaces are used to group related interfaces so that they can be easy to maintain. The nested interface must be referred by the outer interface or class. It can't be accessed directly. Points to remember for nested interfaces Nested interface must be public if it is declared inside the interface but it can have any access modifier if declared within the class. Nested interfaces are declared static implicitly.

Nested Interface Syntax of nested interface which is declared within the interface interface interface_name{ ... interface nested_interface_name{ } class class_name{ ... interface nested_interface_name{ }

Output:hello nested interface Nested Interface – Example-1 interface Showable { void show(); interface Message{ void msg(); } class TestNestedInterface1 implements Showable.Message{ public void msg() { System.out.println("Hello nested interface"); } public static void main(String args[]){ Showable.Message message=new TestNestedInterface1(); //upcasting here message.msg(); Output:hello nested interface

Output:hello nested interface Nested Interface – Example-2 class A{ interface Message{ void msg(); } class TestNestedInterface2 implements A.Message{ public void msg() { System.out.println("Hello nested interface"); } public static void main(String args[]){ A.Message message=new TestNestedInterface2(); //upcasting here message.msg(); Output:hello nested interface

Difference between Abstract class and Interface Abstract class achieves partial abstraction (0 to 100%) Interface achieves fully abstraction (100%).

Difference between Abstract class and Interface interface A{ //Creating interface that has 4 methods void a(); //bydefault, public and abstract void b(); void c(); void d(); } //Creating abstract class that provides the implementation of one method of A interface abstract class B implements A { public void c() { System.out.println("I am C"); } } //Creating subclass of abstract class, now we need to provide the implementation of rest of the methods class M extends B{ public void a() { System.out.println("I am a"); } public void b() { System.out.println("I am b"); } public void d() { System.out.println("I am d"); } //Creating a test class that calls the methods of A interface class Test5{ public static void main(String args[]){ A a=new M(); a.a(); a.b(); a.c(); a.d(); } } Output I am a I am b I am c I am d