Java Note
Java Note
Apart from these concepts, there are some other terms which are used in Object-Oriented design:
o Coupling
o Cohesion
o Association
o Aggregation
o Composition
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual object. Class
doesn't consume any space.
Object
Objects have states and behaviors. Example: A dog has states - color, name, breed as well as
behaviors – wagging the tail, barking, eating. An object is an instance of a class.
Example:
class Student {
String name;
int age;
public void getInfo() {
System.out.println("The name of this Student is " + this.name);
System.out.println("The age of this Student is " + this.age);
}
}
public class OOPS {
public static void main(String args[]) {
Student s1 = new Student();
s1.name = "Aman";
s1.age = 24;
s1.getInfo();
Student s2 = new Student();
extends Keyword
extends is the keyword used to inherit the properties of a class. Following is the syntax of extends
keyword.
Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
Compile Time Polymorphism: The polymorphism which is implemented at the compile time is
known as compile-time polymorphism. Example - Method Overloading
Method Overloading: Method overloading is a technique which allows you to have more
than one function with the same function name but with different functionality. Method overloading
can be possible on the following basis:
1. The return type of the overloaded function.
2. The type of the parameters passed to the function.
3. The number of parameters passed to the function.
Abstraction
Abstraction is a process of hiding the implementation details from the user, only the functionality
will be provided to the user.
In other words, the user will have the information on what the object does instead of how it does it.
In Java, abstraction is achieved using Abstract classes and interfaces.
Abstraction is achieved in 2 ways:
• Abstract class
• Interfaces (Pure Abstraction)
Abstract Class
• An abstract class must be declared with an abstract keyword.
• It can have abstract and non-abstract methods.
• It cannot be instantiated.
• It can have constructors and static methods also.
• It can have final methods which will force the subclass not to change the body of the method.
Code:
interface Animal {
void walk();
}
class Horse implements Animal {
public void walk() {
System.out.println("Horse walks on 4 legs");
}
}
class Chicken implements Animal {
public void walk() {
System.out.println("Chicken walks on 2 legs");
}
}
public class OOPS {
public static void main(String args[]) {
Horse horse = new Horse();
horse.walk();
}
}
Code:
/* File name: EncapTest.java */
public class EncapTest {
private String name;
private String idNum;
private int age;
References,
• JavaTpoint
• GeeksForGeeks
• TutorialsPoint
• Oracle Java Documentations
• And Self Explored
Must Visit,
• Explore More from my GitHub