publicclassSuperKeywordExample{
publicstaticvoidmain(String[] args){
ChildClass obj = new ChildClass();
obj.showData();
System.out.println("\nInside the non-child class");
System.out.println("ChildClass num = " + obj.num);
//System.out.println("ParentClass num = " + super.num); //super can't be used here
}
}
CE204 Object-Oriented Programming
super to refer parent class method
When both parent class and child class have method with the same name,
then the super keyword is used to refer to the parent class method from child class.
CE204 Object-Oriented Programming
super to refer parent class method
classParentClass{
int num1 = 10;
voidshowData(){
System.out.println("\nInside the ParentClass showData method");
System.out.println("ChildClass num = " + num1);
}
}
CE204 Object-Oriented Programming
super to refer parent class method
classChildClassextendsParentClass{
int num2 = 20;
voidshowData(){
System.out.println("\nInside the ChildClass showData method");
System.out.println("ChildClass num = " + num2);
super.showData();
}
}
CE204 Object-Oriented Programming
super to refer parent class method
publicclassSuperKeywordExample{
publicstaticvoidmain(String[] args){
ChildClass obj = new ChildClass();
obj.showData();
//super.showData(); // super can't be used here
}
}
CE204 Object-Oriented Programming
super to call parent class constructor
When an object of child class is created, it automatically calls the parent class default-constructor before it's own.
But, the parameterized constructor of parent class must be called explicitly using the super keyword inside the child class constructor.
CE204 Object-Oriented Programming
super to call parent class constructor
classParentClass{
int num1;
ParentClass(){
System.out.println("\nInside the ParentClass default constructor");
num1 = 10;
}
ParentClass(int value){
System.out.println("\nInside the ParentClass parameterized constructor");
num1 = value;
}
}
CE204 Object-Oriented Programming
super to call parent class constructor
classChildClassextendsParentClass{
int num2;
ChildClass(){
super(100);
System.out.println("\nInside the ChildClass constructor");
num2 = 200;
}
}
CE204 Object-Oriented Programming
super to call parent class constructor
publicclassSuperKeywordExample{
publicstaticvoidmain(String[] args){
ChildClass obj = new ChildClass();
}
}
CE204 Object-Oriented Programming
super to call parent class constructor
To call the parameterized constructor of the parent class,
the super keyword must be the first statement inside the child class constructor,
and we must pass the parameter values.
CE204 Object-Oriented Programming
Access Overridden Methods of the superclass
If methods with the same name are defined in both superclass and subclass, the method in the subclass overrides the method in the superclass. This is called method overriding.
CE204 Object-Oriented Programming
Example 1: Method overriding
classAnimal{
// overridden methodpublicvoiddisplay(){
System.out.println("I am an animal");
}
}
CE204 Object-Oriented Programming
Example 1: Method overriding
classDogextendsAnimal{
// overriding method@Overridepublicvoiddisplay(){
System.out.println("I am a dog");
}
publicvoidprintMessage(){
display();
}
}
CE204 Object-Oriented Programming
Example 1: Method overriding
classMain{
publicstaticvoidmain(String[] args){
Dog dog1 = new Dog();
dog1.printMessage();
}
}
CE204 Object-Oriented Programming
Example 1: Method overriding
In this example, by making an object dog1 of Dog class, we can call its method printMessage() which then executes the display() statement.
Since display() is defined in both the classes, the method of subclass Dog overrides the method of superclass Animal. Hence, the display() of the subclass is called.
CE204 Object-Oriented Programming
Example 1: Method overriding
CE204 Object-Oriented Programming
What if the overridden method of the superclass has to be called?
We use super.display() if the overridden method display() of superclass Animal needs to be called.
CE204 Object-Oriented Programming
Example 2: super to Call Superclass Method
classAnimal{
// overridden methodpublicvoiddisplay(){
System.out.println("I am an animal");
}
}
CE204 Object-Oriented Programming
Example 2: super to Call Superclass Method
classDogextendsAnimal{
// overriding method@Overridepublicvoiddisplay(){
System.out.println("I am a dog");
}
publicvoidprintMessage(){
// this calls overriding method
display();
// this calls overridden methodsuper.display();
}
}
CE204 Object-Oriented Programming
Example 2: super to Call Superclass Method
classMain{
publicstaticvoidmain(String[] args){
Dog dog1 = new Dog();
dog1.printMessage();
}
}
CE204 Object-Oriented Programming
Example 2: super to Call Superclass Method
CE204 Object-Oriented Programming
Access Attributes of the Superclass
The superclass and subclass can have attributes with the same name.
We use the super keyword to access the attribute of the superclass.
CE204 Object-Oriented Programming
Example 3: Access superclass attribute
classAnimal{
protected String type="animal";
}
classDogextendsAnimal{
public String type="mammal";
publicvoidprintType(){
System.out.println("I am a " + type);
System.out.println("I am an " + super.type);
}
}
CE204 Object-Oriented Programming
Example 3: Access superclass attribute
classMain{
publicstaticvoidmain(String[] args){
Dog dog1 = new Dog();
dog1.printType();
}
}
CE204 Object-Oriented Programming
Example 3: Access superclass attribute
In this example, we have defined the same instance field type in both the superclass Animal and the subclass Dog.
We then created an object dog1 of the Dog class. Then, the printType() method is called using this object.
Inside the printType() function,
type refers to the attribute of the subclass Dog.
super.type refers to the attribute of the superclass Animal.
CE204 Object-Oriented Programming
Use of super() to access superclass constructor
As we know, when an object of a class is created, its default constructor is automatically called.
To explicitly call the superclass constructor from the subclass constructor, we use super(). It's a special form of the super keyword.
super() can be used only inside the subclass constructor and must be the first statement.
CE204 Object-Oriented Programming
Example 4: Use of super()
classAnimal{
// default or no-arg constructor of class Animal
Animal() {
System.out.println("I am an animal");
}
}
CE204 Object-Oriented Programming
Example 4: Use of super()
classDogextendsAnimal{
// default or no-arg constructor of class Dog
Dog() {
// calling default constructor of the superclasssuper();
System.out.println("I am a dog");
}
}
CE204 Object-Oriented Programming
Example 4: Use of super()
classMain{
publicstaticvoidmain(String[] args){
Dog dog1 = new Dog();
}
}
CE204 Object-Oriented Programming
Example 4: Use of super()
when an object dog1 of Dog class is created, it automatically calls the default or no-arg constructor of that class.
Inside the subclass constructor, the super() statement calls the constructor of the superclass and executes the statements inside it. Hence, we get the output I am an animal.
CE204 Object-Oriented Programming
Example 4: Use of super()
The flow of the program then returns back to the subclass constructor and executes the remaining statements. Thus, I am a dog will be printed.
However, using super() is not compulsory. Even if super() is not used in the subclass constructor, the compiler implicitly calls the default constructor of the superclass.
CE204 Object-Oriented Programming
Example 4: Use of super()
So, why use redundant code if the compiler automatically invokes super()?
It is required if the parameterized constructor (a constructor that takes arguments) of the superclass has to be called from the subclass constructor.
The parameterized super() must always be the first statement
in the body of the constructor of the subclass,
otherwise, we get a compilation error.
CE204 Object-Oriented Programming
Example 5: Call Parameterized Constructor Using super()
classAnimal{
// default or no-arg constructor
Animal() {
System.out.println("I am an animal");
}
// parameterized constructor
Animal(String type) {
System.out.println("Type: "+type);
}
}
CE204 Object-Oriented Programming
Example 5: Call Parameterized Constructor Using super()
classDogextendsAnimal{
// default constructor
Dog() {
// calling parameterized constructor of the superclasssuper("Animal");
System.out.println("I am a dog");
}
}
CE204 Object-Oriented Programming
Example 5: Call Parameterized Constructor Using super()
classMain{
publicstaticvoidmain(String[] args){
Dog dog1 = new Dog();
}
}
CE204 Object-Oriented Programming
Example 5: Call Parameterized Constructor Using super()
If a parameterized constructor has to be called, we need to explicitly define it in the subclass constructor.
CE204 Object-Oriented Programming
Example 5: Call Parameterized Constructor Using super()
Note that in the above example, we explicitly called the parameterized constructor super("Animal"). The compiler does not call the default constructor of the superclass in this case.
CE204 Object-Oriented Programming
Java final keyword
CE204 Object-Oriented Programming
Java final keyword
In java, the final is a keyword and it is used with the following things.
With variable (to create constant)
With method (to avoid method overriding)
With class (to avoid inheritance)
CE204 Object-Oriented Programming
Java final restrictions
the final variable cannot be reinitialized with another value
the final method cannot be overridden
the final class cannot be extended
CE204 Object-Oriented Programming
final with variables
When a variable defined with the final keyword,
it becomes a constant, and
it does not allow us to modify the value.
The variable defined with the final keyword allows only a one-time assignment,
once a value assigned to it,
never allows us to change it again.
CE204 Object-Oriented Programming
final with variables example-1
publicclassFinalVariableExample{
publicstaticvoidmain(String[] args){
finalint a = 10;
System.out.println("a = " + a);
a = 100; // Can't be modified
}
}
CE204 Object-Oriented Programming
final with variables example-2
classMain{
publicstaticvoidmain(String[] args){
// create a final variablefinalint AGE = 32;
// try to change the final variable
AGE = 45;
System.out.println("Age: " + AGE);
}
}
CE204 Object-Oriented Programming
final with variables recommendation
It is recommended to use uppercase to declare final variables in Java.
CE204 Object-Oriented Programming
final with methods
When a method defined with the final keyword,
it does not allow it to override.
The final method extends to the child class,
but the child class can not override or re-define it.
It must be used as it has implemented in the parent class.
CE204 Object-Oriented Programming
final with methods example-1
classParentClass{
int num = 10;
finalvoidshowData(){
System.out.println("Inside ParentClass showData() method");
System.out.println("num = " + num);
}
}
classFinalDemo{
// create a final methodpublicfinalvoiddisplay(){
System.out.println("This is a final method.");
}
}
classMainextendsFinalDemo{
// try to override final methodpublicfinalvoiddisplay(){
System.out.println("The final method is overridden.");
}
publicstaticvoidmain(String[] args){
Main obj = new Main();
obj.display();
}
}
CE204 Object-Oriented Programming
final with class
When a class defined with final keyword, it can not be extended by any other class.
CE204 Object-Oriented Programming
final with class example-1
finalclassParentClass{
int num = 10;
voidshowData(){
System.out.println("Inside ParentClass showData() method");
System.out.println("num = " + num);
}
}
CE204 Object-Oriented Programming
final with class example-1
classChildClassextendsParentClass{
}
CE204 Object-Oriented Programming
final with class example-1
publicclassFinalKeywordExample{
publicstaticvoidmain(String[] args){
ChildClass obj = new ChildClass();
}
}
CE204 Object-Oriented Programming
final with class example-2
// create a final classfinalclassFinalClass{
publicvoiddisplay(){
System.out.println("This is a final method.");
}
}
// try to extend the final classclassMainextendsFinalClass{
publicvoiddisplay(){
System.out.println("The final method is overridden.");
}
publicstaticvoidmain(String[] args){
Main obj = new Main();
obj.display();
}
}
CE204 Object-Oriented Programming
Java Polymorphism
CE204 Object-Oriented Programming
Java Polymorphism
The polymorphism is the process of defining same method with different implementation. That means creating multiple methods with different behaviors.
In java, polymorphism implemented using
method overloading and
method overriding.
CE204 Object-Oriented Programming
Ad hoc polymorphism
The ad hoc polymorphism is a technique used to define
the same method with different implementations and
different arguments.
In a java programming language, ad hoc polymorphism carried out with
a method overloading concept.
CE204 Object-Oriented Programming
Ad hoc polymorphism
In ad hoc polymorphism the method binding happens at the time of compilation.
Ad hoc polymorphism is also known as compile-time polymorphism.
Every function call binded with the respective overloaded method based on the arguments.
CE204 Object-Oriented Programming
Ad hoc polymorphism
The ad hoc polymorphism implemented within the class only.
classMain{
publicstaticvoidmain(String[] args){
// create an object of Java class
Java j1 = new Java();
j1.displayInfo();
// create an object of Language class
Language l1 = new Language();
l1.displayInfo();
}
}
CE204 Object-Oriented Programming
Polymorphism using method overriding example-2
CE204 Object-Oriented Programming
Java Method Overloading
In a Java class, we can create methods with the same name if they differ in parameters. For example
This is known as method overloading in Java. Here, the same method will perform different operations based on the parameter.
CE204 Object-Oriented Programming
Polymorphism using method overloading example-3
classPattern{
// method without parameterpublicvoiddisplay(){
for (int i = 0; i < 10; i++) {
System.out.print("*");
}
}
// method with single parameterpublicvoiddisplay(char symbol){
for (int i = 0; i < 10; i++) {
System.out.print(symbol);
}
}
}
CE204 Object-Oriented Programming
Polymorphism using method overloading example-3
classMain{
publicstaticvoidmain(String[] args){
Pattern d1 = new Pattern();
// call method without any argument
d1.display();
System.out.println("\n");
// call method with a single argument
d1.display('#');
}
}
CE204 Object-Oriented Programming
Polymorphic Variables
A variable is called polymorphic if it refers to different values under different conditions.
Object variables (instance variables) represent the behavior of polymorphic variables in Java.
It is because object variables of a class can refer to objects of its class as well as objects of its subclasses.
CE204 Object-Oriented Programming
Polymorphic Variables Example-1
classProgrammingLanguage{
publicvoiddisplay(){
System.out.println("I am Programming Language.");
}
}
CE204 Object-Oriented Programming
Polymorphic Variables Example-1
classJavaextendsProgrammingLanguage{
@Overridepublicvoiddisplay(){
System.out.println("I am Object-Oriented Programming Language.");
}
}
CE204 Object-Oriented Programming
Polymorphic Variables Example-1
classMain{
publicstaticvoidmain(String[] args){
// declare an object variable
ProgrammingLanguage pl;
// create object of ProgrammingLanguage
pl = new ProgrammingLanguage();
pl.display();
// create object of Java class
pl = new Java();
pl.display();
}
}
CE204 Object-Oriented Programming
Java Encapsulation
CE204 Object-Oriented Programming
Java Encapsulation
It prevents outer classes from accessing and changing fields and methods of a class. This also helps to achieve data hiding
CE204 Object-Oriented Programming
Java Encapsulation Example
classArea{
// fields to calculate areaint length;
int breadth;
// constructor to initialize values
Area(int length, int breadth) {
this.length = length;
this.breadth = breadth;
}
// method to calculate areapublicvoidgetArea(){
int area = length * breadth;
System.out.println("Area: " + area);
}
}
CE204 Object-Oriented Programming
Java Encapsulation Example
classMain{
publicstaticvoidmain(String[] args){
// create object of Area// pass value of length and breadth
Area rectangle = new Area(5, 6);
rectangle.getArea();
}
}
We can also achieve data hiding using encapsulation.
In the next example,
if we change the length and breadth variable into private,
then the access to these fields is restricted.
And, they are kept hidden from outer classes.
This is called data hiding.
CE204 Object-Oriented Programming
Why Encapsulation?
classArea{
// fields to calculate areaint length;
int breadth;
// constructor to initialize values
Area(int length, int breadth) {
this.length = length;
this.breadth = breadth;
}
// method to calculate areapublicvoidgetArea(){
int area = length * breadth;
System.out.println("Area: " + area);
}
}
CE204 Object-Oriented Programming
Why Encapsulation?
classMain{
publicstaticvoidmain(String[] args){
// create object of Area// pass value of length and breadth
Area rectangle = new Area(5, 6);
rectangle.getArea();
}
}
CE204 Object-Oriented Programming
Data Hiding
Data hiding is a way of restricting the access of our data members by hiding the implementation details.
Encapsulation also provides a way for data hiding.
We can use access modifiers to achieve data hiding
CE204 Object-Oriented Programming
Data hiding using the private specifier example
Making age private allowed us to restrict unauthorized access from outside the class. This is data hiding.
classMain{
publicstaticvoidmain(String[] args){
// create an object of Person
Person p1 = new Person();
// change age using setter
p1.setAge(24);
// access age using getter
System.out.println("My age is " + p1.getAge());
}
}
CE204 Object-Oriented Programming
Java Method Overriding
CE204 Object-Oriented Programming
Java Method Overriding
The method overriding is the process of re-defining a method in a child class that is already defined in the parent class.
When both parent and child classes have the same method, then that method is said to be the overriding method.
The method overriding enables the child class to change the implementation of the method which aquired from parent class according to its requirement.
CE204 Object-Oriented Programming
Java Method Overriding
The method overriding is also known as
dynamic method dispatch or
run time polymorphism or
pure polymorphism.
CE204 Object-Oriented Programming
Java Method Overriding Example
classParentClass{
int num = 10;
voidshowData(){
System.out.println("Inside ParentClass showData() method");
System.out.println("num = " + num);
}
}
publicclassPurePolymorphism{
publicstaticvoidmain(String[] args){
ParentClass obj = new ParentClass();
obj.showData();
obj = new ChildClass();
obj.showData();
}
}
CE204 Object-Oriented Programming
Rules for method overriding
While overriding a method, we must follow the below list of rules.
Static methods can not be overridden.
Final methods can not be overridden.
Private methods can not be overridden.
Constructor can not be overridden.
An abstract method must be overridden.
Use super keyword to invoke overridden method from child class.
CE204 Object-Oriented Programming
Rules for method overriding
The return type of the overriding method must be same as the parent has it.
The access specifier of the overriding method can be changed, but the visibility must increase but not decrease. For example, a protected method in the parent class can be made public, but not private, in the child class.
CE204 Object-Oriented Programming
Rules for method overriding
If the overridden method does not throw an exception in the parent class, then the child class overriding method can only throw the unchecked exception, throwing a checked exception is not allowed.
If the parent class overridden method does throw an exception, then the child class overriding method can only throw the same, or subclass exception, or it may not throw any exception.
CE204 Object-Oriented Programming
Method Overriding Example
classAnimal{
publicvoiddisplayInfo(){
System.out.println("I am an animal.");
}
}
classDogextendsAnimal{
@OverridepublicvoiddisplayInfo(){
System.out.println("I am a dog.");
}
}
classMain{
publicstaticvoidmain(String[] args){
Dog d1 = new Dog();
d1.displayInfo();
}
}
CE204 Object-Oriented Programming
Method Overriding Example
annotations are the metadata that we used to provide information to the compiler
It is not mandatory to use @Override. However, when we use this, the method should follow all the rules of overriding. Otherwise, the compiler will generate an error.
CE204 Object-Oriented Programming
Method Overriding Example
CE204 Object-Oriented Programming
super Keyword in Java Overriding
Can we access the method of the superclass after overriding?
The answer is Yes. To access the method of the superclass from the subclass, we use the super keyword
CE204 Object-Oriented Programming
Use of super Keyword Example
classAnimal{
publicvoiddisplayInfo(){
System.out.println("I am an animal.");
}
}
classDogextendsAnimal{
publicvoiddisplayInfo(){
super.displayInfo();
System.out.println("I am a dog.");
}
}
classMain{
publicstaticvoidmain(String[] args){
Dog d1 = new Dog();
d1.displayInfo();
}
}
CE204 Object-Oriented Programming
Use of super Keyword Example
In the above example, the subclass Dog overrides the method displayInfo() of the superclass Animal.
When we call the method displayInfo() using the d1 object of the Dog subclass, the method inside the Dog subclass is called; the method inside the superclass is not called
Inside displayInfo() of the Dog subclass, we have used super.displayInfo() to call displayInfo() of the superclass.
CE204 Object-Oriented Programming
Use of super Keyword Example
note that constructors in Java are not inherited. Hence, there is no such thing as constructor overriding in Java.
However, we can call the constructor of the superclass from its subclasses. For that, we use super()
CE204 Object-Oriented Programming
Access Specifiers in Method Overriding
The same method declared in the superclass and its subclasses can have different access specifiers. However, there is a restriction.
We can only use those access specifiers in subclasses that provide larger access than the access specifier of the superclass. For example,
Suppose, a method myClass() in the superclass is declared protected. Then, the same method myClass() in the subclass can be either public or protected, but not private.
CE204 Object-Oriented Programming
Access Specifier in Overriding Example
classAnimal{
protectedvoiddisplayInfo(){
System.out.println("I am an animal.");
}
}
classDogextendsAnimal{
publicvoiddisplayInfo(){
System.out.println("I am a dog.");
}
}
classMain{
publicstaticvoidmain(String[] args){
Dog d1 = new Dog();
d1.displayInfo();
}
}
CE204 Object-Oriented Programming
Access Specifier in Overriding Example
In the above example, the subclass Dog overrides the method displayInfo() of the superclass Animal.
Whenever we call displayInfo() using the d1 (object of the subclass), the method inside the subclass is called.
Notice that, the displayInfo() is declared protected in the Animal superclass. The same method has the public access specifier in the Dog subclass.
This is possible because the public provides larger access than the protected.
CE204 Object-Oriented Programming
Overriding Abstract Methods
In Java, abstract classes are created to be the superclass of other classes.
And, if a class contains an abstract method,
it is mandatory to override it.
CE204 Object-Oriented Programming
Java Nested and Inner Class
CE204 Object-Oriented Programming
Java Nested and Inner Class
In Java, you can define a class within another class.
There are two types of nested classes you can create in Java.
Non-static nested class (inner class)
Static nested class
CE204 Object-Oriented Programming
Non-Static Nested Class (Inner Class)
A non-static nested class is a class within another class.
It has access to members of the enclosing class (outer class).
It is commonly known as inner class.
Since the inner class exists within the outer class,
you must instantiate the outer class first,
in order to instantiate the inner class.
CE204 Object-Oriented Programming
Non-Static Nested Class (Inner Class) Example
classCPU{
double price;
// nested classclassProcessor{
// members of nested classdouble cores;
String manufacturer;
doublegetCache(){
return4.3;
}
}
// nested protected classprotectedclassRAM{
// members of protected nested classdouble memory;
String manufacturer;
doublegetClockSpeed(){
return5.5;
}
}
}
CE204 Object-Oriented Programming
Non-Static Nested Class (Inner Class) Example
publicclassMain{
publicstaticvoidmain(String[] args){
// create object of Outer class CPU
CPU cpu = new CPU();
// create an object of inner class Processor using outer class
CPU.Processor processor = cpu.new Processor();
// create an object of inner class RAM using outer class CPU
CPU.RAM ram = cpu.new RAM();
System.out.println("Processor Cache = " + processor.getCache());
System.out.println("Ram Clock speed = " + ram.getClockSpeed());
}
}
CE204 Object-Oriented Programming
Non-Static Nested Class (Inner Class) Example
In the example program, there are two nested classes:
Processor and RAM inside the outer class:
CPU.
We can declare the inner class as protected.
Hence, we have declared the RAM class as protected.
Inside the Main class,
we first created an instance of an outer class CPU named cpu.
Using the instance of the outer class, we then created objects of inner classes
Accessing Members of Outer Class within Inner Class Example
publicclassMain{
publicstaticvoidmain(String[] args){
// create an object of the outer class Car
Car car1 = new Car("Mazda", "8WD");
// create an object of inner class using the outer class
Car.Engine engine = car1.new Engine();
engine.setEngine();
System.out.println("Engine Type for 8WD= " + engine.getEngineType());
Car car2 = new Car("Crysler", "4WD");
Car.Engine c2engine = car2.new Engine();
c2engine.setEngine();
System.out.println("Engine Type for 4WD = " + c2engine.getEngineType());
}
}
CE204 Object-Oriented Programming
Accessing Members of Outer Class within Inner Class Example
In the example program, we have the inner class named
Engine inside the outer class Car. Here, notice the line,
if(Car.this.carType.equals("4WD")) {...}
We are using this keyword to access the carType variable of the outer class.
You may have noticed that instead of using this.carType we have used Car.this.carType
CE204 Object-Oriented Programming
Accessing Members of Outer Class within Inner Class Example
It is because if we had not mentioned the name of the outer class Car,
then this keyword will represent the member inside the inner class.
Similarly, we are also accessing the method of the outer class from the inner class.
if (Car.this.getCarName().equals("Crysler") {...}
It is important to note that, although the getCarName() is a private method, we are able to access it from the inner class.
CE204 Object-Oriented Programming
Static Nested Class
In Java, we can also define a static class inside another class.
Such class is known as static nested class.
Static nested classes are not called static inner classes.
Unlike inner class, a static nested class cannot access the member variables of the outer class.
It is because the static nested class doesn't require you to create an instance of the outer class.
OuterClass.NestedClass obj = new OuterClass.NestedClass();
Here, we are creating an object of the static nested class by simply using the class name of the outer class.
Hence, the outer class cannot be referenced using OuterClass.this.
publicclassMain{
publicstaticvoidmain(String[] args){
// create an object of the static nested class// using the name of the outer class
MotherBoard.USB usb = new MotherBoard.USB();
System.out.println("Total Ports = " + usb.getTotalPorts());
}
}
CE204 Object-Oriented Programming
Static Inner Class Example
In the above program, we have created a static class named USB inside the class MotherBoard. Notice the line,
MotherBoard.USB usb = new MotherBoard.USB();
Here, we are creating an object of USB using the name of the outer class.
Now, let's see what would happen if you try to access the members of the outer class:
CE204 Object-Oriented Programming
Accessing members of Outer class inside Static Inner Class Example
classMotherBoard{
String model;
publicMotherBoard(String model){
this.model = model;
}
// static nested classstaticclassUSB{
int usb2 = 2;
int usb3 = 1;
intgetTotalPorts(){
// accessing the variable model of the outer classsif(MotherBoard.this.model.equals("MSI")) {
return4;
}
else {
return usb2 + usb3;
}
}
}
}
CE204 Object-Oriented Programming
Accessing members of Outer class inside Static Inner Class Example
publicclassMain{
publicstaticvoidmain(String[] args){
// create an object of the static nested class
MotherBoard.USB usb = new MotherBoard.USB();
System.out.println("Total Ports = " + usb.getTotalPorts());
}
}
CE204 Object-Oriented Programming
Accessing members of Outer class inside Static Inner Class Example
When we try to run the program, we will get an error:
error: non-static variable this cannot be referenced from a static context
This is because we are not using the object of the outer class to create an object of the inner class.
Hence, there is no reference to the outer class Motherboard stored in Motherboard.this.
CE204 Object-Oriented Programming
Key Points to Remember
Java treats the inner class as a regular member of a class. They are just like methods and variables declared inside a class.
Since inner classes are members of the outer class, you can apply any access modifiers like private, protected to your inner class which is not possible in normal classes.
Since the nested class is a member of its enclosing outer class, you can use the dot (.) notation to access the nested class and its members.
Using the nested class will make your code more readable and provide better encapsulation.
Non-static nested classes (inner classes) have access to other members of the outer/enclosing class, even if they are declared private.
CE204 Object-Oriented Programming
Java Nested Static Class
CE204 Object-Oriented Programming
Java Nested Static Class
we can have a class inside another class in Java. Such classes are known as nested classes. In Java, nested classes are of two types:
Nested non-static class (Inner class)
Nested static class.
CE204 Object-Oriented Programming
Java Nested Static Class
We use the keyword static to make our nested class static.
Note: In Java, only nested classes are allowed to be static.
Like regular classes, static nested classes can include both static and non-static fields and methods. For example,
Class Animal {
staticclassMammal{
// static and non-static members of Mammal
}
// members of Animal
}
Static nested classes are associated with the outer class.
To access the static nested class, we don’t need objects of the outer class.
CE204 Object-Oriented Programming
Static Nested Class Example
classAnimal{
// inner classclassReptile{
publicvoiddisplayInfo(){
System.out.println("I am a reptile.");
}
}
// static classstaticclassMammal{
publicvoiddisplayInfo(){
System.out.println("I am a mammal.");
}
}
}
CE204 Object-Oriented Programming
Static Nested Class Example
classMain{
publicstaticvoidmain(String[] args){
// object creation of the outer class
Animal animal = new Animal();
// object creation of the non-static class
Animal.Reptile reptile = animal.new Reptile();
reptile.displayInfo();
// object creation of the static nested class
Animal.Mammal mammal = new Animal.Mammal();
mammal.displayInfo();
}
}
CE204 Object-Oriented Programming
Static Nested Class Example
In the example program, we have two nested class Mammal and Reptile inside a class Animal.
To create an object of the non-static class Reptile, we have used
Animal.Reptile reptile = animal.new Reptile()
To create an object of the static class Mammal, we have used
Animal.Mammal mammal = new Animal.Mammal()
CE204 Object-Oriented Programming
Accessing Members of Outer Class
In Java, static nested classes are associated with the outer class.
This is why static nested classes can only access the class members (static fields and methods) of the outer class.
CE204 Object-Oriented Programming
Accessing Non-static members Example
classAnimal{
staticclassMammal{
publicvoiddisplayInfo(){
System.out.println("I am a mammal.");
}
}
classReptile{
publicvoiddisplayInfo(){
System.out.println("I am a reptile.");
}
}
publicvoideat(){
System.out.println("I eat food.");
}
}
Main.java:1: error: modifier static not allowed here
static class Animal {
^
1 error
compiler exit status 1
In the example, we have tried to create a static class Animal.
Since Java doesn’t allow static top-level class,
we will get an error.
CE204 Object-Oriented Programming
Java Anonymous Class
CE204 Object-Oriented Programming
Java Anonymous Class
In Java, a class can contain another class known as nested class. It's possible to create a nested class without giving any name.
A nested class that doesn't have any name is known as an anonymous class.
An anonymous class must be defined inside another class. Hence, it is also known as an anonymous inner class. Its syntax is:
classouterClass{
// defining anonymous class
object1 = new Type(parameterList) {
// body of the anonymous class
};
}
CE204 Object-Oriented Programming
Java Anonymous Class
Anonymous classes usually extend subclasses or implement interfaces.
Here, Type can be
a superclass that an anonymous class extends
an interface that an anonymous class implements
The above code creates an object, object1, of an anonymous class at runtime.
Note: Anonymous classes are defined inside an expression. So, the semicolon is used at the end of anonymous classes to indicate the end of the expression.
CE204 Object-Oriented Programming
Anonymous Class Extending a Class Example
classPolygon{
publicvoiddisplay(){
System.out.println("Inside the Polygon class");
}
}
classAnonymousDemo{
publicvoidcreateClass(){
// creation of anonymous class extending class Polygon
Polygon p1 = new Polygon() {
publicvoiddisplay(){
System.out.println("Inside an anonymous class.");
}
};
p1.display();
}
}
CE204 Object-Oriented Programming
Anonymous Class Extending a Class Example
classMain{
publicstaticvoidmain(String[] args){
AnonymousDemo an = new AnonymousDemo();
an.createClass();
}
}
CE204 Object-Oriented Programming
Anonymous Class Extending a Class Example
In the example, we have created a class Polygon. It has a single method display().
We then created an anonymous class that extends the class Polygon and overrides the display() method.
When we run the program, an object p1 of the anonymous class is created.
The object then calls the display() method of the anonymous class.
CE204 Object-Oriented Programming
Anonymous Class Implementing an Interface Example
interfacePolygon{
publicvoiddisplay();
}
classAnonymousDemo{
publicvoidcreateClass(){
// anonymous class implementing interface
Polygon p1 = new Polygon() {
publicvoiddisplay(){
System.out.println("Inside an anonymous class.");
}
};
p1.display();
}
}
CE204 Object-Oriented Programming
Anonymous Class Implementing an Interface Example
classMain{
publicstaticvoidmain(String[] args){
AnonymousDemo an = new AnonymousDemo();
an.createClass();
}
}
In the example, we have created an anonymous class that implements the Polygon interface.
CE204 Object-Oriented Programming
Advantages of Anonymous Classes
In anonymous classes, objects are created whenever they are required.
That is, objects are created to perform some specific tasks. For example,
Object = new Example() {
publicvoiddisplay(){
System.out.println("Anonymous class overrides the method display().");
}
};
Here, an object of the anonymous class is created dynamically when we need to override the display() method.
Anonymous classes also help us to make our code concise.
CE204 Object-Oriented Programming
Java enums
CE204 Object-Oriented Programming
Java enums
In Java, an enum (short for enumeration) is a type that has a fixed set of constant values. We use the enum keyword to declare enums. For example,
enumSize{
SMALL, MEDIUM, LARGE, EXTRALARGE
}
Here, we have created an enum named Size. It contains fixed values SMALL, MEDIUM, LARGE, and EXTRALARGE.
These values inside the braces are called enum constants (values).
Note: The enum constants are usually represented in uppercase.
classTest{
Size pizzaSize;
publicTest(Size pizzaSize){
this.pizzaSize = pizzaSize;
}
publicvoidorderPizza(){
switch(pizzaSize) {
case SMALL:
System.out.println("I ordered a small size pizza.");
break;
case MEDIUM:
System.out.println("I ordered a medium size pizza.");
break;
default:
System.out.println("I don't know which one to order.");
break;
}
}
}
CE204 Object-Oriented Programming
Java Enum with the switch statement example
classMain{
publicstaticvoidmain(String[] args){
Test t1 = new Test(Size.MEDIUM);
t1.orderPizza();
}
}
CE204 Object-Oriented Programming
Java Enum with the switch statement example
In the example, we have created an enum type Size. - We then declared a variable pizzaSize of the Size type.
Here, the variable pizzaSize can only be assigned with 4 values (SMALL, MEDIUM, LARGE, EXTRALARGE).
Notice the statement,
Test t1 = new Test(Size.MEDIUM);
It will call the Test() constructor inside the Test class. Now, the variable pizzaSize is assigned with the MEDIUM constant.
Based on the value, one of the cases of the switch case statement is executed.
CE204 Object-Oriented Programming
Enum Class in Java
In Java, enum types are considered to be a special type of class.
It was introduced with the release of Java 5.
An enum class can include methods and fields just like regular classes.
enumSize{
constant1, constant2, …, constantN;
// methods and fields
}
When we create an enum class, the compiler will create instances (objects) of each enum constants.
Also, all enum constant is always public static final by default.
CE204 Object-Oriented Programming
Java Enum Class Example
enumSize{
SMALL, MEDIUM, LARGE, EXTRALARGE;
public String getSize(){
// this will refer to the object SMALLswitch(this) {
case SMALL:
return"small";
case MEDIUM:
return"medium";
case LARGE:
return"large";
case EXTRALARGE:
return"extra large";
default:
returnnull;
}
}
...
CE204 Object-Oriented Programming
Java Enum Class Example
...
publicstaticvoidmain(String[] args){
// call getSize()// using the object SMALL
System.out.println("The size of the pizza is " + Size.SMALL.getSize());
}
}
CE204 Object-Oriented Programming
Java Enum Class Example
In the example, we have created an enum class Size. It has four constants SMALL, MEDIUM, LARGE and EXTRALARGE.
Since Size is an enum class, the compiler automatically creates instances for each enum constants.
Here inside the main() method, we have used the instance SMALL to call the getSize() method.
Note: Like regular classes, an enum class also may include constructors
CE204 Object-Oriented Programming
Methods of Java Enum Class
There are some predefined methods in enum classes that are readily available for use.
CE204 Object-Oriented Programming
Methods of Java Enum Class
Java Enum ordinal()
The ordinal() method returns the position of an enum constant. For example,
ordinal(SMALL)
// returns 0
CE204 Object-Oriented Programming
Methods of Java Enum Class
Enum compareTo()
The compareTo() method compares the enum constants based on their ordinal value. For example,
The constructor takes a string value as a parameter and assigns value to the variable pizzaSize.
Since the constructor is private,
we cannot access it from outside the class. However,
we can use enum constants to call the constructor.
In the Main class, we assigned SMALL to an enum variable size.
The constant SMALL then calls the constructor Size with string as an argument.
Finally, we called getSize() using size.
CE204 Object-Oriented Programming
Java enum Strings
CE204 Object-Oriented Programming
Java enum Strings
In Java, we can get the string representation of enum constants using the toString() method or the name() method. For example,
enumSize{
SMALL, MEDIUM, LARGE, EXTRALARGE
}
classMain{
publicstaticvoidmain(String[] args){
System.out.println("string value of SMALL is " + Size.SMALL.toString());
System.out.println("string value of MEDIUM is " + Size.MEDIUM.name());
}
}
we have seen the default string representation of an enum constant is the name of the same constant.
CE204 Object-Oriented Programming
Change Default String Value of enums
We can change the default string representation of enum constants by overriding the toString() method. For example,
enumSize{
SMALL {
// overriding toString() for SMALLpublic String toString(){
return"The size is small.";
}
},
MEDIUM {
// overriding toString() for MEDIUMpublic String toString(){
return"The size is medium.";
}
};
}
...
In the above program, we have created an enum Size. And we have overridden the toString() method for enum constants SMALL and MEDIUM.
Note: We cannot override the name() method. It is because the name() method is final.
CE204 Object-Oriented Programming
Java Abstract Class
CE204 Object-Oriented Programming
Java Abstract Class
An abstract class is a class that created using abstract keyword. In other words, a class prefixed with abstract keyword is known as an abstract class.
In java, an abstract class may contain abstract methods (methods without implementation) and also non-abstract methods (methods with implementation).
We use the following syntax to create an abstract class.
abstractclass <ClassName>{
...
}
CE204 Object-Oriented Programming
Java Abstract Class Example-1
import java.util.*;
abstractclassShape{
int length, breadth, radius;
Scanner input = new Scanner(System.in);
abstractvoidprintArea();
}
CE204 Object-Oriented Programming
Java Abstract Class Example-1
classRectangleextendsShape{
voidprintArea(){
System.out.println("*** Finding the Area of Rectangle ***");
System.out.print("Enter length and breadth: ");
length = input.nextInt();
breadth = input.nextInt();
System.out.println("The area of Rectangle is: " + length * breadth);
}
}
CE204 Object-Oriented Programming
Java Abstract Class Example-1
classTriangleextendsShape{
voidprintArea(){
System.out.println("\n*** Finding the Area of Triangle ***");
System.out.print("Enter Base And Height: ");
length = input.nextInt();
breadth = input.nextInt();
System.out.println("The area of Triangle is: " + (length * breadth) / 2);
}
}
CE204 Object-Oriented Programming
Java Abstract Class Example-1
classCricleextendsShape{
voidprintArea(){
System.out.println("\n*** Finding the Area of Cricle ***");
System.out.print("Enter Radius: ");
radius = input.nextInt();
System.out.println("The area of Cricle is: " + 3.14f * radius * radius);
}
}
CE204 Object-Oriented Programming
Java Abstract Class Example-1
publicclassAbstractClassExample{
publicstaticvoidmain(String[] args){
Rectangle rec = new Rectangle();
rec.printArea();
Triangle tri = new Triangle();
tri.printArea();
Cricle cri = new Cricle();
cri.printArea();
}
}
CE204 Object-Oriented Programming
Java Abstract Class Example-1
An abstract class can not be instantiated but can be referenced.
That means we can not create an object of an abstract class,
but base reference can be created.
CE204 Object-Oriented Programming
Java Abstract Class Example-1
In the example program, the child class objects are created to invoke the overridden abstract method.
But we may also create base class reference and assign it with child class instance to invoke the same.
The main method of the above program can be written as follows that produce the same output.
CE204 Object-Oriented Programming
Java Abstract Class Example-1
publicstaticvoidmain(String[] args){
Shape obj = new Rectangle(); //Base class reference to Child class instance
obj.printArea();
obj = new Triangle();
obj.printArea();
obj = new Cricle();
obj.printArea();
}
CE204 Object-Oriented Programming
Java Abstract Class Example-2
abstractclassAnimal{
abstractvoidmakeSound();
publicvoideat(){
System.out.println("I can eat.");
}
}
CE204 Object-Oriented Programming
Java Abstract Class Example-2
classDogextendsAnimal{
// provide implementation of abstract methodpublicvoidmakeSound(){
System.out.println("Bark bark");
}
}
CE204 Object-Oriented Programming
Java Abstract Class Example-2
classMain{
publicstaticvoidmain(String[] args){
// create an object of Dog class
Dog d1 = new Dog();
d1.makeSound();
d1.eat();
}
}
CE204 Object-Oriented Programming
Java Abstract Class Example-3
abstractclassMotorBike{
abstractvoidbrake();
}
CE204 Object-Oriented Programming
Java Abstract Class Example-3
classSportsBikeextendsMotorBike{
// implementation of abstract methodpublicvoidbrake(){
System.out.println("SportsBike Brake");
}
}
CE204 Object-Oriented Programming
Java Abstract Class Example-3
classMountainBikeextendsMotorBike{
// implementation of abstract methodpublicvoidbrake(){
System.out.println("MountainBike Brake");
}
}
CE204 Object-Oriented Programming
Java Abstract Class Example-3
classMain{
publicstaticvoidmain(String[] args){
MountainBike m1 = new MountainBike();
m1.brake();
SportsBike s1 = new SportsBike();
s1.brake();
}
}
CE204 Object-Oriented Programming
Accesses Constructor of Abstract Classes
An abstract class can have constructors like the regular class. And, we can access the constructor of an abstract class from the subclass using the super keyword. For example,
Note that the super should always be the first statement of the subclass constructor
CE204 Object-Oriented Programming
Java Abstract Class
Rules for method overriding
An abstract class must follow the below list of rules.
An abstract class must be created with abstract keyword.
An abstract class can be created without any abstract method.
An abstract class may contain abstract methods and non-abstract methods.
An abstract class may contain final methods that can not be overridden.
CE204 Object-Oriented Programming
Java Abstract Class
Rules for method overriding
An abstract class may contain static methods, but the abstract method can not be static.
An abstract class may have a constructor that gets executed when the child class object created.
An abstract method must be overridden by the child class, otherwise, it must be defined as an abstract class.
An abstract class can not be instantiated but can be referenced.
CE204 Object-Oriented Programming
Java Abstract Class Review
CE204 Object-Oriented Programming
Java Abstract Class Review
The abstract class in Java cannot be instantiated (we cannot create objects of abstract classes). We use the abstract keyword to declare an abstract class. For example,
// create an abstract classabstractclassLanguage{
// fields and methods
}
...
// try to create an object Language// throws an error
Language obj = new Language();
CE204 Object-Oriented Programming
Java Abstract Class Review
An abstract class can have both the regular methods and abstract methods. For example,
A method that doesn't have its body is known as an abstract method. We use the same abstract keyword to create abstract methods. For example,
abstractvoiddisplay();
Here, display() is an abstract method. The body of display() is replaced by ;.
If a class contains an abstract method, then the class should be declared abstract. Otherwise, it will generate an error. For example,
// error// class should be abstractclassLanguage{
// abstract methodabstractvoidmethod1();
}
CE204 Object-Oriented Programming
Java Abstract Class and Method Example
Though abstract classes cannot be instantiated, we can create subclasses from it. We can then access members of the abstract class using the object of the subclass.
CE204 Object-Oriented Programming
Java Abstract Class and Method Example
abstractclassLanguage{
// method of abstract classpublicvoiddisplay(){
System.out.println("This is Java Programming");
}
}
classMainextendsLanguage{
publicstaticvoidmain(String[] args){
// create an object of Main
Main obj = new Main();
// access method of abstract class// using object of Main class
obj.display();
}
}
CE204 Object-Oriented Programming
Java Abstract Class and Method Example
In the example, we have created an abstract class named Language. The class contains a regular method display().
We have created the Main class that inherits the abstract class. Notice the statement,
obj.display();
Here, obj is the object of the child class Main. We are calling the method of the abstract class using the object obj.
CE204 Object-Oriented Programming
Java Abstract Method Review Keypoints
We use the abstract keyword to create abstract classes and methods.
An abstract method doesn't have any implementation (method body).
A class containing abstract methods should also be abstract.
We cannot create objects of an abstract class.
To implement features of an abstract class, we inherit subclasses from it and create objects of the subclass.
A subclass must override all abstract methods of an abstract class. However, if the subclass is declared abstract, it's not mandatory to override abstract methods.
We can access the static attributes and methods of an abstract class using the reference of the abstract class. For example,
Animal.staticMethod();
CE204 Object-Oriented Programming
Java Object Class
CE204 Object-Oriented Programming
Java Object Class
In java, the Object class is the super most class of any class hierarchy.
The Object class in the java programming language is present inside the java.lang package.
Every class in the java programming language is a subclass of Object class by default.
The Object class is useful when you want to refer to any object whose type you don't know.
Because it is the superclass of all other classes in java,
it can refer to any type of object.
CE204 Object-Oriented Programming
Methods of Object class
object getClass()
Returns Class class object
int hashCode()
returns the hashcode number for object being used.
boolean equals(Object obj)
compares the argument object to calling object.
int clone()
Compares two strings, ignoring case
CE204 Object-Oriented Programming
Methods of Object class
object concat(String)
Creates copy of invoking object
String toString()
Returns the string representation of invoking object.
void notify()
Wakes up a thread, waiting on invoking object's monitor.
void notifyAll()
wakes up all the threads, waiting on invoking object's - monitor.
CE204 Object-Oriented Programming
Methods of Object class
void wait()
causes the current thread to wait, until another thread - notifies
void wait(long,int)
causes the current thread to wait for the specified - milliseconds and nanoseconds, until another thread notifies.
void finalize()
It is invoked by the garbage collector before an object is being garbage collected.
CE204 Object-Oriented Programming
Java Forms of Inheritance
The inheritance concept used for the number of purposes in the java programming language.
One of the main purposes is substitutability.
The substitutability means that when a child class acquires properties from its parent class, the object of the parent class may be substituted with the child class object.
For example, if B is a child class of A, anywhere we expect an instance of A we can use an instance of B.
The substitutability can achieve using inheritance, whether using extends or implements keywords.
CE204 Object-Oriented Programming
Java Forms of Inheritance
The following are the differnt forms of inheritance in java.
Specialization
Specification
Construction
Extension
Limitation
Combination
CE204 Object-Oriented Programming
Java Forms of Inheritance
Specialization
It is the most ideal form of inheritance. The subclass is a special case of the parent class. It holds the principle of substitutability.
CE204 Object-Oriented Programming
Java Forms of Inheritance
Specification
This is another commonly used form of inheritance. In this form of inheritance, the parent class just specifies which methods should be available to the child class but doesn't implement them. The java provides concepts like abstract and interfaces to support this form of inheritance. It holds the principle of substitutability.
CE204 Object-Oriented Programming
Java Forms of Inheritance
Construction
This is another form of inheritance where the child class may change the behavior defined by the parent class (overriding). It does not hold the principle of substitutability.
CE204 Object-Oriented Programming
Java Forms of Inheritance
Extension
This is another form of inheritance where the child class may add its new properties. It holds the principle of substitutability.
CE204 Object-Oriented Programming
Java Forms of Inheritance
Limitation
This is another form of inheritance where the subclass restricts the inherited behavior. It does not hold the principle of substitutability.
CE204 Object-Oriented Programming
Java Forms of Inheritance
Combination
This is another form of inheritance where the subclass inherits properties from multiple parent classes. Java does not support multiple inheritance type.
CE204 Object-Oriented Programming
Benefits and Costs of Inheritance in java
Inheritance is the core and more useful concept of Object-Oriented Programming.
It proWith inheritance, we will be able to override the methods of the base class so that the meaningful implementation of the base class method can be designed in the derived class.
An inheritance leads to less development and maintenance costs. Vides many benefits, and a few of them are listed below.
CE204 Object-Oriented Programming
Benefits of Inheritance
Inheritance helps in code reuse. The child class may use the code defined in the parent class without re-writing it.
Inheritance can save time and effort as the main code need not be written again.
Inheritance provides a clear model structure which is easy to understand.
An inheritance leads to less development and maintenance costs.
With inheritance, we will be able to override the methods of the base class so that the meaningful implementation of the base class method can be designed in the derived class. An inheritance leads to less development and maintenance costs.
In inheritance base class can decide to keep some data private so that it cannot be altered by the derived class.
CE204 Object-Oriented Programming
Costs of Inheritance
Inheritance decreases the execution speed due to the increased time and effort it takes, the program to jump through all the levels of overloaded classes.
Inheritance makes the two classes (base and inherited class) get tightly coupled. This means one cannot be used independently of each other.
The changes made in the parent class will affect the behavior of child class too.
The overuse of inheritance makes the program more complex.
CE204 Object-Oriented Programming
Defining Packages in java
CE204 Object-Oriented Programming
Defining Packages in java
In java, a package is a container of classes,
interfaces, and
sub-packages.
We may think of it as a folder in a file directory.
We use the packages to
avoid naming conflicts and
to organize
project-related
classes,
interfaces, and
sub-packages into a bundle.
CE204 Object-Oriented Programming
Defining Packages in java
In java, the packages have divided into two types.
Built-in Packages
User-defined Packages
CE204 Object-Oriented Programming
Built-in Packages
The built-in packages are the packages from java API. The Java API is a library of pre-defined classes, interfaces, and sub-packages.
The built-in packages were included in the JDK.
There are many built-in packages in java, few of them are as java, lang, io, util, awt, javax, swing, net, sql, etc.
We need to import the built-in packages to use them in our program.
To import a package, we use the import statement.
CE204 Object-Oriented Programming
User-defined Packages
The user-defined packages are the packages created by the user.
User is free to create their own packages.
CE204 Object-Oriented Programming
Definig a Package in java
We use the package keyword to create or define a package in java programming language.
package packageName;
CE204 Object-Oriented Programming
Definig a Package in java
The package statement must be the first statement in the program.
The package name must be a single word.
The package name must use Camel case notation.
CE204 Object-Oriented Programming
Definig a Package in java
create a user-defined package myPackage
package myPackage;
publicclassDefiningPackage{
publicstaticvoidmain(String[] args){
System.out.println("This class belongs to myPackage.");
}
}
CE204 Object-Oriented Programming
Definig a Package in java
Now, save the example code in a file DefiningPackage.java, and compile it using the following command.
javac -d . DefiningPackage.java
The above command creates a directory with the package name myPackage, and the DefiningPackage.class is saved into it.
Run the program use the following command.
java myPackage.DefiningPackage
When we use IDE like Eclipse, Netbeans, etc. the package structure is created automatically.
CE204 Object-Oriented Programming
Access protection in java packages
In java, the access modifiers define the accessibility of the class and its members.
For example, private members are accessible within the same class members only. Java has four access modifiers, and they are default, private, protected, and public.
In java, the package is a container of classes, sub-classes, interfaces, and sub-packages. The class acts as a container of data and methods. So, the access modifier decides the accessibility of class members across the different packages.
In java, the accessibility of the members of a class or interface depends on its access specifiers.
CE204 Object-Oriented Programming
Access protection in java packages
CE204 Object-Oriented Programming
Access protection in java packages
The public members can be accessed everywhere.
The private members can be accessed only inside the same class.
The protected members are accessible to every child class (same package or other packages).
The default members are accessible within the same package but not outside the package.
CE204 Object-Oriented Programming
Access protection in java packages example
classParentClass{
int a = 10;
publicint b = 20;
protectedint c = 30;
privateint d = 40;
voidshowData(){
System.out.println("Inside ParentClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
In java, the import keyword used to import built-in and user-defined packages. When a package has imported, we can refer to all the classes of that package using their name directly.
The import statement must be after the package statement, and before any other statement.
Using an import statement, we may import a specific class or all the classes from a package.
CE204 Object-Oriented Programming
Importing Packages in java
Using one import statement, we may import only one package or a class.
Using an import statement, we can not import a class directly, but it must be a part of a package.
A program may contain any number of import statements.
CE204 Object-Oriented Programming
Importing specific class
import packageName.ClassName;
CE204 Object-Oriented Programming
Importing specific class
import a built-in package and Scanner class.
package myPackage;
import java.util.Scanner;
publicclassImportingExample{
publicstaticvoidmain(String[] args){
Scanner read = new Scanner(System.in);
int i = read.nextInt();
System.out.println("You have entered a number " + i);
}
}
CE204 Object-Oriented Programming
Importing all the classes
Using an importing statement, we can import all the classes of a package. To import all the classes of the package, we use * symbol.
The following syntax is employed to import all the classes of a package.
import packageName.*;
CE204 Object-Oriented Programming
Importing all the classes
import a built-in package.
package myPackage;
import java.util.*;
publicclassImportingExample{
publicstaticvoidmain(String[] args){
Scanner read = new Scanner(System.in);
int i = read.nextInt();
System.out.println("You have entered a number " + i);
Random rand = new Random();
int num = rand.nextInt(100);
System.out.println("Randomly generated number " + num);
}
}
CE204 Object-Oriented Programming
Importing all the classes
The import statement imports only classes of the package, but not sub-packages and its classes.
We may also import sub-packages by using a symbol '.' (dot) to separate parent package and sub-package.