There is Constructor Over Loading.
class Car{
int price; // 0
String name; // null
Car(){ // default constructor
}
Car(int p, String s){ // Parameter constructor
price = p;
name = s;
}
Car(String s, int x){
price = x;
name = s;
}
void print(){
System.out.println(price+" "+name);
}
}
public class Constructor_Over_Loading_In_OOP {
public static void main(String[] args) {
Car c1 = new Car(1250000,"Kia Sonet");
Car c2 = new Car("Lord Alto",400000);
Car c3 = new Car();
c3.price = 123000;
c3.name = "Honda Amaze";
c1.print();
c2.print();
c3.print();
}
}
We are inheriting parent class to child class.
// Parent class
class Animal {
void eat() {
System.out.println("This animal eats food");
}
}
// Child class
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
// Main class
public class Inherit_Parent_Class_To_Child_Class_In_OOP {
public static void main(String[] args) {
Dog d = new Dog();
d.eat(); // inherited method
d.bark(); // own method
}
}
There are some Member Of Class With Static Keyword.
class Cricketer{
static String country = "NZ";
int runs;
String name;
double avg;
void print(){
System.out.println(runs+" "+name+" "+avg);
}
}
public class Member_Of_Class_With_Static_Keyword_In_OOP {
public static void main(String[] args) {
Cricketer c1 = new Cricketer();
Cricketer c2 = new Cricketer();
c1.country = "India";
System.out.println(c2.country);
}
}
We are passing array to constructor.
import java.util.Arrays;
class StudentData{
String name;
int rno;
int[] marks;
StudentData(int[] s){
marks = Arrays.copyOf(s,s.length);
}
StudentData(int s){
marks = new int[s];
}
}
public class Pass_Array_To_Constructor_In_OOP {
public static void main(String[] args) {
int[] arr = {4,7,1,4,8};
StudentData s1 = new StudentData(arr);
s1.marks[0] = 40;
System.out.println(arr[0]);
System.out.println(s1.marks[0]);
StudentData s2 = new StudentData(2);
}
}
There is PolyMorphism Concept.
public class PolyMorphism_Concept_In_OOP {
public static class Dog{
void speak(){
System.out.println("Bhau Bhau");
}
}
public static class Cat{
void speak(){
System.out.println("Meow Meow");
}
}
public static class Lion{
void speak(){
System.out.println("GRRRRRR");
}
}
public static class Pikachu{
void speak(){
System.out.println("Pika Pika");
}
}
public static class Human{
void speak(){
System.out.println("Hello");
}
}
public static void main(String[] args) {
Dog tommy = new Dog();
Cat c = new Cat();
Human bishal = new Human();
Pikachu p = new Pikachu();
tommy.speak();
c.speak();
p.speak();
bishal.speak();
}
}