0% found this document useful (0 votes)
27 views23 pages

Coding Unit II

The document covers various concepts in Java including inheritance, interfaces, abstract classes, final variables, methods, and classes, as well as packages. It provides code examples demonstrating these concepts, such as the use of the super keyword, dynamic method dispatch, and the implementation of interfaces. Additionally, it explains the purpose of packages in Java and the advantages of using them for organizing code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views23 pages

Coding Unit II

The document covers various concepts in Java including inheritance, interfaces, abstract classes, final variables, methods, and classes, as well as packages. It provides code examples demonstrating these concepts, such as the use of the super keyword, dynamic method dispatch, and the implementation of interfaces. Additionally, it explains the purpose of packages in Java and the advantages of using them for organizing code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

UNIT II INHERITANCE, PACKAGE AND INTERFACE

SUPER KEYWORD

class book
{
int a;
String name="Java the complete reference";
}
class course extends book
{
int a;
String name="Object Oriented Programming using Java";
void display()
{
System.out.println("Text Book name:"+super.name);
System.out.println("Coursename:"+name);
}
public static void main(String[] args)
{
course c=new course();
c.display();
}
}

// Online Java Compiler


// Use this editor to write, compile and run your Java code online

class book
{
int a=3;
String name="Java the complete reference";
void display()
{
System.out.println("Sem"+this.a);
}
}
class course extends book
{
int a=4;
String name="Object Oriented Programming using Java";
void display()
{
System.out.println("Text Book name:"+super.name);
System.out.println("Course number:"+this.a);
System.out.println("Coursename:"+name);
super.display();
}
public static void main(String[] args)
{
course c=new course();
c.display();
}
--------------------------------------------------------------------------------------------------------
------------------------------

interface

interface Polygon
{
void Area(); // default method
default void Sides()
{
System.out.println("I can get sides of a polygon.");
}
}// implements the interface

class Rectangle implements Polygon


{
public void Area()
{
int length = 6;
int breadth = 5;
int area = length * breadth;
System.out.println("The area of the rectangle is " + area);
} // overrides the getSides()
public void Sides()
{
System.out.println("I have 4 sides.");
}
}// implements the interface

class Square implements Polygon


{
public void Area()
{
int length = 5;
int area = length * length;
System.out.println("The area of the square is " + area);
}
public static void main(String[] args)
{ // create an object of Rectangle
Rectangle r1 = new Rectangle();
r1.Area();
r1.Sides(); // create an object of Square
Square s1 = new Square();
s1.Area();
s1.Sides();
}
}

—----------------------------------------------------------------------------------------
---------------------
Interface example2
import java.util.*;
interface Area
{
public void Square();
public void Circle();
public void Rectangle();
public void Triangle();
}
public class shapeArea implements Area
{
public void Circle()
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter the radius of the circle");
double r = kb.nextInt();
double areaOfCircle = 3.142 * r * r;
System.out.println("Area of the circle is " + areaOfCircle);
}//@Override
public void Square()
{// TODO Auto-generated method stub
Scanner kb2 = new Scanner(System.in);
System.out.println("Enter the length side of the square");
double s = kb2.nextInt();
double areaOfSquare = s * s;
System.out.println("Area of the square is " + areaOfSquare);
}@Override
public void Rectangle()
{// TODO Auto-generated method stub
Scanner kb3 = new Scanner(System.in);
System.out.println("Enter the length of the Rectangle");
double l = kb3.nextInt();
System.out.println("Enter the breadth of the Rectangle");
double b = kb3.nextInt();
double areaOfRectangle = l * b;
System.out.println("Area of the Rectangle is " +
areaOfRectangle);
}@Override
public void Triangle()
{// TODO Auto-generated method stub
Scanner kb4 = new Scanner(System.in);
System.out.println("Enter the base of the Triangle");
double base = kb4.nextInt();
System.out.println("Enter the height of the Triangle");
double h = kb4.nextInt();
double areaOfTriangle = 0.5 * base * h;
System.out.println("Area of the Triangle is " +
areaOfTriangle);
}
public static void main(String[] args) {
shapeArea geometry = new shapeArea();
geometry.Circle();
geometry.Square();
geometry.Rectangle();
geometry.Triangle();
}
}
output:
Enter the radius of the circle
5
Area of the circle is 78.55
Enter the length side of the square
5
Area of the square is 25.0
Enter the length of the Rectangle
5
Enter the breadth of the Rectangle
5
Area of the Rectangle is 25.0
Enter the base of the Triangle
5
Enter the height of the Triangle
5
Area of the Triangle is 12.5
—-----------------------------------------

interface b
{

void book();
}

class oops implements b


{
protected String j = "Java the complete reference 11 edition";
public void book()
{
System.out.println("Course Name: Object Oriented
Programming using Java");
}
}

class csd extends oops {


private String cc= "22CDT31";
public static void main(String[] args)
{
csd c = new csd();
System.out.println("The course code:" +c.cc);

c.book();
System.out.println("Text book name:" +c.j);
}
}
output:

The course code:22CDT31


Course Name: Object Oriented Programming using Java
Text book name:Java the complete reference 11 edition

—----------------------------------------------------------------------------------------
-------------------------------------------

Dynamic method dispatch


class apple
{
void display()
{
System.out.println("Welcome to fruit shop");
System.out.println("Parent class: Apple");
}
}
class banana extends apple
{
void display()
{
System.out.println("child class: Banana");
}
}
class cherry extends apple
{
void display()
{
System.out.println("Child class: Cherrry");
}
}
class dates extends apple
{
void display()
{
System.out.println("Child class: Dates");
}
public static void main(String args[])
{
apple a=new apple();
banana b= new banana();
cherry c= new cherry();
dates d=new dates();
apple ref;
ref=a;
a.display();
ref=b;
b.display();
ref=c;
c.display();
ref=d;
d.display();
}

}
output:
Welcome to fruit shopParent class: Apple
child class: Banana
Child class: Cherrry
Child class: Dates

ABSTRACT CLASS:
A few properties of the abstract classes are:

● Abstract methods may or may not be present in the Java


abstract class.
● The presence of at least one abstract method in a class makes
the class an abstract class.
● An abstract class cannot have any objects and therefore
cannot be directly instantiated.
● An abstract class can be used only if it is inherited from
another class and implements the abstract methods.
● Proper implementations of the abstract methods are required
while inheriting an abstract class.
● Both regular and abstract methods can be present in a Java
abstract class.
● Parameterized constructors may be present in an abstract
class. Also, an abstract class always contains a default
constructor.

Top Features Of Abstract Class

The top features of an abstract class are listed below-

● Code reusability
● Template
● Loose coupling
● Abstraction
● Dynamic resolution

There are five important rules you must follow when using abstract

classes in Java. These are listed below-

1. The keyword “abstract” must be used mandatorily when


declaring an abstract class in Java.
2. Abstract class cannot directly get instantiated.
3. Abstract class needs to have at least one method that is
abstract. An abstract class always contains final methods.
4. Such classes might also comprise non-abstract methods.
5. Abstract class might comprise constructors as well as static
methods

The keyword “abstract” is used for abstract classes and methods in Java.

The abstract class has the abstract keyword in its declaration.

The syntax of a Java abstract class is:

abstract class class_name

public abstract void the_abstractMethod();

public void the_normalMethod()

#body of the method

EXAMPLE1:
abstract class Shape
{
public abstract double getArea();
public abstract double getPerimeter();
}
class Rectangle extends Shape {
private double length;
private double width;

public Rectangle(double length, double width) {


this.length = length;
this.width = width;
}
public double getArea() {
return length * width;
}
public double getPerimeter() {
return 2 * (length + width);
}
}
class Circle extends Shape {
private double radius;

public Circle(double radius) {


this.radius = radius;
}

public double getArea() {


return Math.PI * radius * radius;
}

public double getPerimeter() {


return 2 * Math.PI * radius;
}
}
class Triangle extends Shape {
private double side1;
private double side2;
private double side3;

public Triangle(double side1, double side2, double side3) {


this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}

public double getArea() {


double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}

public double getPerimeter() {


return side1 + side2 + side3;
}
public static void main(String[] args) {
// create some shapes
Shape rectangle = new Rectangle(10, 12);
Shape circle = new Circle(5);
Shape triangle = new Triangle(7, 8, 6);

// calculate area and perimeter of each shape


System.out.println("\nArea and perimeter of various shapes:");
System.out.println("\nRectangle: Length-10, Width-12");
System.out.println("Area: " + rectangle.getArea());
System.out.println("Perimeter: " + rectangle.getPerimeter());

System.out.println("\nCircle: Radius-5");
System.out.println("Area: " + circle.getArea());
System.out.println("Perimeter: " + circle.getPerimeter());

System.out.println("\nTriangle: Side1-7, Side2-8, Side3-6");


System.out.println("Area: " + triangle.getArea());
System.out.println("Perimeter: " + triangle.getPerimeter());
}
}
—-------------------------------------------------------------------------------------------
FINAL VARIABLE, METHOD AND CLASS

The final keyword in java is used to restrict


the user. The java final keyword can be used in
many context. Final can be:

1. variable 2. method 3.class

Final variable improves performance


during runtime.
We cannot override the final method in
java.
EXAMPLE: FINAL VARIABLE
public class finalvar
{
public static void main (String[] args)
{
final int count=10;
System.out.println("Count value is "+count);
}
}
output: Count value is 10
—---------------------------------------------------------

EXAMPLE: FINAL MEHTOD AND CLASS


class FinalClassExample
{
public final void display()
{
System.out.println("This is a final
method.");
}
}
public class Test extends
FinalClassExample
{
public void display1()
{
System.out.println("Overriding the
final method.");
}
public static void main(String[] args)
{
Test obj = new Test();
obj.display();
obj.display1();
}
}
output:
This is a final method.
Overriding the final method.
—-----------------------------------------------------------------------------------------------------
------------------------------
PACKAGE
A package in Java is used to group related classes. Think of it
as a folder in a file directory. We use packages to avoid name
conflicts, and to write a better maintainable code.

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.

Packages are divided into two categories:

● Built-in Packages (packages from the Java API)


● User-defined Packages (create your own packages)

Advantage

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.

Built-in Packages (packages from the Java API)


import java.util.Scanner;

java, lang, awt, javax, swing, net, io, util, sql etc.

1. Java.lang: lang stands for language. The Java language


package consists of java classes and interfaces that form the
core of the Java language and the JVM.
It is a fundamental package that is useful for writing and
executing all Java programs. Examples are classes, objects,
String, Thread, predefined data types, etc. It is imported
automatically into the Java programs.
2. Java.io: io stands for input and output. It provides a set of
I/O streams that are used to read and write data to files.
A stream represents a flow of data from one place to another
place.
3. Java util: util stands for utility. It contains a collection of
useful utility classes and related interfaces that implement
data structures like LinkedList, Dictionary, HashTable,
stack, vector, Calender, data utility, etc.
4. Java.net: net stands for network. It contains networking
classes and interfaces for networking operations. The
programming related to client-server can be done by using
this package.

Example:

import java.util.Scanner; // import the Scanner class

class Main {

public static void main(String[] args) {

Scanner myObj = new Scanner(System.in);

String userName;
// Enter username and press Enter

System.out.println("Enter username");

userName = myObj.nextLine();

System.out.println("Username is: " + userName);

output:

Enter username

Username is: hh

User-defined Packages (create your own packages)


To create your own package, you need to understand that Java
uses a file system directory to store them. Just like folders on
your computer:

└── root
└── mypack
└── MyPackageClass.java

Example:

package mypack;

class MyPackageClass {
public static void main(String[] args) {

System.out.println("This is my package!");

This is my package!

Example: //save by A.java


package pack;

public class A

public void msg(){System.out.println("Hello");}

—----------------------------------

//save by B.java

package mypack;

import pack.A;

class B{

public static void main(String args[]){

A obj = new A();

obj.msg();

Output:Hello
1. What is a Package in Java?
A Package is a collection of files of the type Java
Class, Interfaces, or Abstract Class

A Package usually contains Java Classes written for a


specific purpose or problem

A Package is simply a Directory or Folder with Java


Classes

2. Choose the correct syntax of a Java Package below

package PACKAGE_NAME;

3. The name of a package is the name of the _____ in Java.


Folder

All parent folders separated by DOT symbols

All parent packages separated by DOT symbols


All the above

4. It is possible to declare a package and import another


package within the same Java class file. possible

5. The keyword used to import a package into a Java class


or Interface is import

6. Which is the correct syntax to import a Java package


below?
import PACKAGE1.PACKAGE2.PACKAGE3.*;

import PACKAGE1.*;

import PACKAGE1.CLASS1;

All the above

7. We can use the same name for a Parent package and


Child package in Java. true
8. Choose a correct statement below about importing
packages into a class.
A Java class or interface can import any number of packages

It is advised to import only the required Classes of a package to save


memory

Java packages are usually distributed in the form of JAR files

All the above

9. When importing a Package, the Class is actually


importing
Classes or Interfaces from the package
10. Which is the default Java package that will be
auto-included (imported) in the classpath while
compiling and running a Java program?
java.io

java.lang

java.net

java.util

java.lang

—----------------------------------------------------------------------------------------------------------

Overview of Unit II MCQ

1. Which cannot be inherited from a base class in Java programming

Constructor

final method

Both

None

You might also like