[go: up one dir, main page]

0% found this document useful (0 votes)
607 views7 pages

Unit - 2 Object Oriented Programming Through Java (B.Tech II-I)

This document discusses object-oriented programming concepts in Java including inheritance, polymorphism, abstraction, and encapsulation. It provides examples of inheritance including: 1. A multilevel inheritance example with classes Animal, Dog which extends Animal, and BabyDog which extends Dog. 2. A hierarchical inheritance example showing subclasses Dog and Cat extending the superclass Animal. 3. Code examples demonstrating method overriding and accessing overridden and superclass methods. Inheritance allows code reuse and establishes an "is-a" relationship between classes.

Uploaded by

Raju
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)
607 views7 pages

Unit - 2 Object Oriented Programming Through Java (B.Tech II-I)

This document discusses object-oriented programming concepts in Java including inheritance, polymorphism, abstraction, and encapsulation. It provides examples of inheritance including: 1. A multilevel inheritance example with classes Animal, Dog which extends Animal, and BabyDog which extends Dog. 2. A hierarchical inheritance example showing subclasses Dog and Cat extending the superclass Animal. 3. Code examples demonstrating method overriding and accessing overridden and superclass methods. Inheritance allows code reuse and establishes an "is-a" relationship between classes.

Uploaded by

Raju
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
You are on page 1/ 7

Unit - 2

Object Oriented Programming Through Java (B.Tech II-I)


UNI T-2: Inheritance: Basics, Using Super, Creating Multilevel components. The man only knows that pressing the
hierarchy, Method overriding, Dynamic Method Dispatch, Using accelerators will increase the speed of car or applying brakes
Abstract classes, Using final with inheritance, Object class, will stop the car but he does not know about how on pressing
Polymorphism- dynamic binding, method overriding, abstract the accelerator the speed is actually increasing, he does not
classes and methods. know about the inner mechanism of the car or the
Packages: Basics, Finding packages and CLASSPATH, Access implementation of accelerator, brakes etc in the car. This is
Protection, Importing packages. what abstraction is.
Inheritance: Class Hierarchy:
• 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.
Use of inheritance in java:
• For Method Overriding (so runtime polymorphism can be Base Class Object:
achieved).  In java all classes use inheritance
• For Code Reusability.  If no parent class is specified explicitly, the base
Terms used in Inheritance class object is simply inherited.
• Class: A class is a group of objects which have common  All classes defined in java, is a child of object class,
properties. It is a template or blueprint from which objects which provides minimal functionality.
are created. Methods defined in Object class are:
• Sub Class/Child Class: Subclass is a class which inherits
the other class. It is also called a derived class, extended  equals(Object obj) Determine whether the argument
class, or child class. object is the same as the receiver.
• Super Class/Parent Class: Superclass is the class from • getClass() Returns the class of the receiver, an object
where a subclass inherits the features. It is also called a
of type Class.
base class or a parent class.
• hashCode() Returns a hash value for this object.
• Reusability: As the name specifies, reusability is a
mechanism which facilitates you to reuse the fields and Should be overridden when the equals method is
methods of the existing class when you create a new class. changed.
You can use the same fields and methods already defined in • toString() Converts object into a string value. This
the previous class. method is also often overridden.
Extends keyword: Subtype:
• The extends keyword indicates that you are making a new • Inheritance relationships are often shown graphically
class that derives from an existing class. The meaning of in a class diagram, with the arrow pointing to the
"extends" is to increase the functionality. parent class.
• In the terminology of Java, a class which is inherited is
called a parent or superclass, and the new class is called
child or subclass.
Hierarchical Abstraction:
An essential element of object oriented programming is abstraction.
Humans manage complexity through abstraction.
Example: Data Abstraction is the property by virtue of which only
the essential details are displayed to the user.The trivial or the non-
essentials units are not displayed to the user. Ex: A car is viewed as
a car rather than its individual Substitutability/Deriving Subclasses:
In Java, we use the reserved word extends to establish an
inheritance relationship

Prepared by G. Pradeep Reddy, Assistant. Prof. Dept. C.S.E, JNTUACEA, Ananthapuramu Page 1
Unit - 2
Object Oriented Programming Through Java (B.Tech II-I)
class Animal Example:
{ Program 2
// class contents class Calculation {
int weight; int z;
public void int getWeight()
{…} public void addition(int x, int y) {
} z = x + y;
class Bird extends Animal System.out.println("The sum of the given numbers:"+z);
{ }
// class contents public void Subtraction(int x, int y) {
public void fly() z = x - y;
{…}; System.out.println("The difference between the given
} numbers:"+z);
Types of inheritance in java: }
}
public class My_Calculation extends Calculation {
public void multiplication(int x, int y) {
z = x * y;
System.out.println("The product of the given
numbers:"+z);
}

public static void main(String args[]) {


int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
}

Program 1
class Employee{ Multilevel Inheritance Example:
float salary=40000; class Animal{
} void eat(){System.out.println("eating...");}
class Programmer extends Employee{ }
int bonus=10000; class Dog extends Animal{
public static void main(String args[]){ void bark(){System.out.println("barking...");}
Programmer p=new Programmer(); }
System.out.println("Programmer salary is:"+p.salary); class BabyDog extends Dog{
System.out.println("Bonus of Programmer is:"+p.bonus); void weep(){System.out.println("weeping...");}
} }
} class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}

Prepared by G. Pradeep Reddy, Assistant. Prof. Dept. C.S.E, JNTUACEA, Ananthapuramu Page 2
Unit - 2
Object Oriented Programming Through Java (B.Tech II-I)
Hierarchical Inheritance Example: class Dog extends Animal { // Subclass (child)
class Animal{ public void animalSound() {
void eat(){System.out.println("eating...");} super.animalSound(); // Call the superclass method
} System.out.println("The dog says: bow wow");
class Dog extends Animal{ }
void bark(){System.out.println("barking...");} }
} public class SuperMain {
class Cat extends Animal{ public static void main(String[] args) {
void meow(){System.out.println("meowing...");} Animal myDog = new Dog(); // Create a Dog object
} myDog.animalSound(); // Call the method on the Dog
class TestInheritance3{ object
public static void main(String args[]){ Puppy pet= new Puppy();
Cat c=new Cat(); pet.animalSound();}
c.meow(); }
c.eat();
//c.bark();//C.T.Error
}}

class Puppy extends Dog { // Subclass (child)


public void animalSound() {
Multiple Inheritance: super.super.animalSound(); // Call the superclass method
class A{ System.out.println("The dog says: small bow wow");
void msg(){System.out.println("Hello");} }
} }
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

public static void main(String args[]){ The java super keyword can fetch data from parent class but
C obj=new C(); not from patents parent class where as it is supported in c++.
obj.msg();//Now which msg() method would be invoked? • It violates encapsulation. You shouldn't be able to
} bypass the parent class's behaviour. It makes sense to
} sometimes be able to bypass your own class's
This scenario is not supported in java to overcome this behaviour (particularly from within the same
difficulty we use Interfaces. method) but not your parent's.
Super Keyword in Java: • In Java, a class cannot directly access the
• The super keyword in java is a reference variable that is grandparent’s members. It is allowed in C++ though.
used to refer parent class objects. In C++, we can use scope resolution operator (::) to
• It is used to call superclass methods, and to access access any ancestor’s member in inheritance
the superclass constructor. The most common use of hierarchy. In Java, we can access grandparent’s
the super keyword is to eliminate the confusion between members only through the parent class.
superclasses and subclasses that have methods with the class Grandparent {
same name. public void Print() {
Program System.out.println("Grandparent's Print()");
class Animal { // Superclass (parent) }
public void animalSound() { }
System.out.println("The animal makes a sound");
} class Parent extends Grandparent {
} public void Print() {
super.Print();
System.out.println("Parent's Print()");
}
}

Prepared by G. Pradeep Reddy, Assistant. Prof. Dept. C.S.E, JNTUACEA, Ananthapuramu Page 3
Unit - 2
Object Oriented Programming Through Java (B.Tech II-I)
class Child extends Parent {
public void Print() { class Student extends Person
super.Print(); {
System.out.println("Child's Print()"); Student()
} {
} // invoke or call parent class constructor
super();
public class Main {
public static void main(String[] args) { System.out.println("Student class Constructor");
Child c = new Child(); }
c.Print(); }
} class Testz
} {
public static void main(String[] args)
{
Student s = new Student();
}
class Vehicle }
{
int maxSpeed = 120;
} Polymorphism:
class Car extends Vehicle • Polymorphism is derived from 2 Greek words: poly
{ and morphs.
int maxSpeed = 180; • we have many classes that are related to each other
void display() by inheritance.
{
• The same entity (method or operator or object) can
/* print maxSpeed of base class (vehicle) */ perform different operations in different scenarios.
System.out.println("Maximum Speed: " + super.maxSpeed);
}
}
class Tests
{
public static void main(String[] args)
{
Car small = new Car(); Runtime polymorphism:
small.display(); public class Animal
} {
} public void sound()
{
System.out.println("Animal is making a sound");
}
}
class Person class Horse extends Animal{
{ public void sound(){
Person() System.out.println("Neigh....");
{ }
System.out.println("Person class Constructor"); public static void main(String args[]){
} Animal obj = new Horse();
} obj.sound();
}}

Prepared by G. Pradeep Reddy, Assistant. Prof. Dept. C.S.E, JNTUACEA, Ananthapuramu Page 4
Unit - 2
Object Oriented Programming Through Java (B.Tech II-I)
Compile time Polymorphism: Abstract Classes and Methods
class Overload Data abstraction is the process of hiding certain details and
{ showing only essential information to the user.
void demo (int a) Abstraction can be achieved with either abstract classes or
{ interfaces (which you will learn more about in the next
System.out.println ("a: " + a); chapter).
}
void demo (int a, int b) The abstract keyword is a non-access modifier, used for
{ classes and methods:
System.out.println ("a and b: " + a + "," + b);
} Abstract class: is a restricted class that cannot be used to
double demo(double a) { create objects (to access it, it must be inherited from another
System.out.println("double a: " + a); class).
return a*a;
} Abstract method: can only be used in an abstract class, and it
} does not have a body. The body is provided by the subclass
class MethodOverloading (inherited from).
{ An abstract class can have both abstract and regular methods:
public static void main (String args []) o An abstract class must be declared with an abstract
{ keyword.
Overload Obj = new Overload(); o It can have abstract and non-abstract methods.
double result; o It cannot be instantiated.
Obj .demo(10); o It can have constructors and static methods also.
Obj .demo(10, 20); o It can have final methods which will force the
result = Obj .demo(5.5); subclass not to change the body of the method.
System.out.println("O/P : " + result); Program:
} abstract class Shape{
} abstract void draw();
}
//In real scenario, implementation is provided by others i.e.
unknown by end user
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In a real scenario, object is provided
through method, e.g., getShape() method
s.draw();
}
}

Prepared by G. Pradeep Reddy, Assistant. Prof. Dept. C.S.E, JNTUACEA, Ananthapuramu Page 5
Unit - 2
Object Oriented Programming Through Java (B.Tech II-I)
In this example, Shape is the abstract class, and its implementation is Commonly Used Standard Packages:
provided by the Rectangle and Circle classes.
Mostly, we don't know about the implementation class (which is
hidden to the end user), and an object of the implementation class is
provided by the factory method.
A factory method is a method that returns the instance of the class.

Package:
• A package is a group of related classes and interfaces.
• Packages provide a way of organizing your code and of
controlling access to the code. Static Import:
• Classes defined within a package must be accessed through • The use of import followed by static allows you to
their package name. import static members of a class.
• When no package is specified, the global (default) no-name • Those static members can then be referred to directly
package is used. by their names, without having to qualify them with
Defining a Package: the name of their class.
• General form: • For example, to use the Math function sqrt( ) in the
package pkgname; form "sqrt( )" instead of "Math.sqrt( )", add one of
• This statement must be at the top of a Java source file. the import statements
• Usually lower case is used for the package name. import static Math.sqrt;
• In the file system, each package is stored in its own import static Math.*;
directory that has the same name as the package. package pack;
public class A{
Using Packages: public void msg(){System.out.println("Hello");}
• You can define packages inside of packages. }
• To put a class in a package pkg2 which is nested inside a
pkg1, use the statement: package mypack;
package pkg1.pkg2; import pack.*;
• To compile MyClass.java that is in the package class B{
pkg1.pkg2, use public static void main(String args[])
javac pgk1/pgk2/MyClass.java {
• To run MyClass, use A obj = new A();
java pgk1.pgk2.MyClass obj.msg();
Importing Packages: }
• To use MyClass, you can use the fully qualified name, as }
follows:
pkg1.pkg2.MyClass v = new pkg1.pkg2.MyClass();
• Or use the import statement with general form:
import pkg.classname;
• Use an asterisk (*) for the classname to import the entire
contents of a package.
• The import statement goes after the package statement and
before any class definitions.
• With imports, you need not qualify MyClass.

Packages and Member Access:

Prepared by G. Pradeep Reddy, Assistant. Prof. Dept. C.S.E, JNTUACEA, Ananthapuramu Page 6
Unit - 2
Object Oriented Programming Through Java (B.Tech II-I)
package pack; package pack;
public class A{ public class A{
public void msg(){System.out.println("Hello");} } public void msg(){System.out.println("Hello");}
package mypack; }
import pack.A; package mypack;
class B{ class B{
public static void main(String args[]){ public static void main(String args[]){
A obj = new A(); pack.A obj = new pack.A();//using fully qualified name
obj.msg(); obj.msg();
} }
} }

How to send the class file to another directory or drive?

• To Compile:
• How to compile java package? If you are not using any • c:\GPR> javac -d c:\classes Simple.java
IDE, you need to follow the syntax given below: • To Run:
• javac -d directory javafilename • To run this program from e:\source directory, you
• For example need to set classpath of the directory where the class
• javac -d . Simple.java file resides. c:\GPR> set classpath=c:\classes;.;
• The -d switch specifies the destination where to put the c:\GPR> java mypack.SimpleAnother way to run
generated class file. You can use any directory name like this program by -classpath switch of java:
/home (in case of Linux), d:/abc (in case of windows) etc. If • The -classpath switch can be used with javac and
you want to keep the package within the same directory, java tool.
you can use . (dot). • To run this program from e:\source directory, you
• How to run java package program can use -classpath switch of java that tells where to
• You need to use fully qualified name e.g. mypack.Simple look for class file. For example:
etc to run the class. • c:\GPR> java -classpath c:\classes mypack.Simple
• To Compile: javac -d . Simple.javaTo Run: java • Output:Welcome to package
mypack.SimpleOutput: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.

Prepared by G. Pradeep Reddy, Assistant. Prof. Dept. C.S.E, JNTUACEA, Ananthapuramu Page 7

You might also like