Oops Unit-Ii
Oops Unit-Ii
1) Method Overriding
2)Code Reusability.
Terms used in Inheritance
• Class: A class is a group of objects which have common properties. It
is a template or blueprint from which objects are created.
• Sub Class/Child Class: Subclass is a class which inherits the other
class. It is also called a derived class, extended class, or child class.
• Super Class/Parent Class: Superclass is the class from where a
subclass inherits the features. It is also called a base class or a parent
class.
• Reusability: As the name specifies, reusability is a mechanism which
facilitates you to reuse the fields and methods of the existing class
when you create a new class. You can use the same fields and methods
already defined in the previous class.
The syntax of Java Inheritance
package mypack;
public class Simple{
public static void main(String args[]) {
System.out.println("Welcome to
package");
}
}
How to run java package program
You need to use fully qualified name e.g. Simple to run the class.
To Compile: javac Simple.java
To Run: java Simple
import package.*;
import package.classname;
fully qualified name.
Sequence of the program must be package then import then class.
How to send the class file to another directory or drive?
package mypack; public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}}
To Compile: e:\sources> javac -d c:\classes Simple.java
To Run: To run this program from e:\source directory, you need to set
classpath of the directory where the class file resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple
Another way to run this program by -classpath switch of java:
• The -classpath switch can be used with javac and java tool.
• To run this program from e:\source directory, you can use -
classpath switch of java that tells where to look for class file.
interface {
// declare constant fields
// declare methods that abstract
// by default.
}
Uses of Interfaces in Java are mentioned below:
A class can extend another class similar to this an interface can extend
another interface. But only a class can extend to another interface, and
vice-versa is not allowed.
Difference Between Class and Interface:
Interface Variables in Java
• Java interfaces provide a way to define a contract or blueprint for
classes to implement. In addition to methods, interfaces can also
include variables.
• These variables, known as interface variables or constants, are a
fundamental aspect of Java interfaces.
• In Java, an interface variable is implicitly public, static, and final.
• This means that the variable's value cannot be changed once it is
assigned.
• Interface variables are accessible to all implementing classes,
promoting code reusability and standardization.
Example:
public interface Shape {
int DEFAULT_SIZE = 10;
void draw();
}