Unit - 2 Object Oriented Programming Through Java (B.Tech II-I)
Unit - 2 Object Oriented Programming Through Java (B.Tech II-I)
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);
}
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
}}
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.
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();
} }
} }
• 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