Sie sind auf Seite 1von 11

Constructor:

, constructor is a block of codes similar to method. It is called when an instance of


object is created and memory is allocated for the object.

Every time an object is created using new() keyword, at least one constructor is called. It
is called a default constructor.

There are basically two rules defined for the constructor.


 Constructor name must be same as its class name
 Constructor must have no explicit return type

There are two types of constructors :


 Default constructor (no-arg constructor)
 Parameterized constructor

A constructor is called "Default Constructor" when it doesn't have any parameter.

class Bike1{

Bike1(){System.out.println("Bike is created");}

public static void main(String args[]){


Bike1 b=new Bike1();
}
}

A constructor which has a specific number of parameters is called parameterized constructor.

class Student4{
int id;
String name;

Student4(int i,String n){


id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}

, a constructor is just like a method but without return type. It can also be overloaded
like Java methods.
Constructor overloading is a technique of having more than one constructor with different
parameter lists. They are arranged in a way that each constructor performs a different task.
They are differentiated by the compiler by the number of parameters in the list and their
types.

class Student5{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}

Static Keyword:
The static keyword is used for memory management mainly.

The static can be:


 variable (also known as class variable)
 method (also known as class method)
 block
 nested class

If you declare any variable as static, it is known static variable.


 The static variable can be used to refer the common property of all objects (that is
not unique for each object) e.g. company name of employees, college name of students
etc.
 The static variable gets memory only once in class area at the time of class loading.

class Student8{
int rollno;
String name;
static String college ="ITS";

Student8(int r,String n){


rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){


Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");

s1.display();
s2.display();
}
}

this Keyword:
this is a reference variable that refers to the current object.

 this can be used to refer current class instance variable.


 this can be used to invoke current class method (implicitly)
 this() can be used to invoke current class constructor.
 this can be passed as an argument in the method call.
 this can be passed as argument in the constructor call.
 this can be used to return the current class instance from the method.
1) this: to refer current class instance variable

parameters (formal arguments) and instance variables are same. So, we are using
this keyword to distinguish local variable and instance variable.

class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}

class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}

2) this: to invoke current class method

You may invoke the method of the current class by using the this keyword. If you
don't use the this keyword, compiler automatically adds this keyword while invoking
the method.

3) this() : to invoke current class constructor

this() constructor call can be used to invoke the current class constructor. It is
used to reuse the constructor. In other words, it is used for constructor chaining.

Calling default constructor from Calling parameterized constructor from


parameterized constructor: default constructor:

class A{ class A{
A(){System.out.println("hello a");} A(){
A(int x){ this(5);
this(); System.out.println("hello a");
System.out.println(x); }
} A(int x){
} System.out.println(x);
class TestThis5{ }
public static void main(String args[]){ }
A a=new A(10); class TestThis6{
}} public static void main(String args[]){
A a=new A();
}}
Inheritance:
Inheritance is a mechanism in which one object acquires all the properties and
behaviours of parent object.

Why use inheritance


 For Method Overriding (so runtime polymorphism can be achieved).
 For 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
previous class.

The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.

class Employee{
float salary=40000;
}

class Programmer extends Employee{


int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}

Types of inheritance:
Single Inheritance:

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}

Multilevel Inheritance:

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}

Hierarchical Inheritance:

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}

Why multiple inheritance is not supported:


To reduce the complexity and simplify the language, multiple inheritance is not
supported.
Consider a scenario where A, B and C are three classes. The C class inherits A and
B classes. If A and B classes have same method and you call it from child class
object, there will be ambiguity to call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile time
error if you inherit 2 classes. So whether you have same method or different, there
will be compile time error now.
Aggregation:
If a class have an entity reference, it is known as Aggregation. Aggregation
represents HAS-A relationship.

class Operation{
int square(int n){
return n*n;
}
}

class Circle{
Operation op;//aggregation
double pi=3.14;

double area(int radius){


op=new Operation();
int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).
return pi*rsquare;
}

public static void main(String args[]){


Circle c=new Circle();
double result=c.area(5);
System.out.println(result);
}
}
 Code reuse is also best achieved by aggregation when there is no is-a
relationship.
 Inheritance should be used only if the relationship is-a is maintained
throughout the lifetime of the objects involved; otherwise, aggregation is the
best choice.

Method Overloading:
If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.

There are two ways to overload the method


 By changing number of arguments
 By changing the data type

Method Overloading: changing no. of Method Overloading: changing data type


arguments: of arguments:

class Adder{ class Adder{


static int add(int a,int b){return static int add(int a, int b){return
a+b;} a+b;}
static int add(int a,int b,int static double add(double a, double
c){return a+b+c;} b){return a+b;}
} }
class TestOverloading1{ class TestOverloading2{
public static void main(String[] args){ public static void main(String[] args){
System.out.println(Adder.add(11,11)); System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11)) System.out.println(Adder.add(12.3,12.6))
; ;
}} }}

method overloading is not possible by changing the return type of the method only
because of ambiguity.
Method Overriding:
If subclass (child class) has the same method as declared in the parent class, it
is known as method overriding .

Usage of Method Overriding:


 Method overriding is used to provide specific implementation of a method that
is already provided by its super class.
 Method overriding is used for runtime polymorphism

Rules for Method Overriding:


 method must have same name as in the parent class
 method must have same parameter as in the parent class.
 must be IS-A relationship (inheritance).

class Bank{
int getRateOfInterest(){return 0;}
}

class SBI extends Bank{


int getRateOfInterest(){return 8;}
}

class ICICI extends Bank{


int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}

class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}

Can we override static method?


No, static method cannot be overridden. It can be proved by runtime polymorphism

Why we cannot override static method?


because static method is bound with class whereas instance method is bound with
object. Static belongs to class area and instance belongs to heap area.

Can we override main method?


No, because main is a static method.

No. Method Overloading Method Overriding


1) Method overloading is used to Method overriding is used to
increase the readability of the provide the specific
program. implementation of the method that
is already provided by its super
class.
2) Method overloading is Method overriding occurs in two
performed within class. classes that have IS-A
(inheritance) relationship.
3) In case of method In case of method
overloading, parameter must be overriding, parameter must be
different. same.
4) Method overloading is the example Method overriding is the example
of compile time polymorphism. of run time polymorphism.
5) , method overloading can't be Return type must be same or
performed by changing return type covariant in method overriding.
of the method only. Return type
can be same or different in method
overloading. But you must have to
change the parameter.

super keyword:
The super keyword is a reference variable which is used to refer immediate parent
class object.

Usage of super Keyword:


 super can be used to refer immediate parent class instance variable.
 super can be used to invoke immediate parent class method.
 super() can be used to invoke immediate parent class constructor.

super is used to refer super can be used to invoke super is used to invoke
immediate parent class parent class method parent class constructor
instance variable:
class Animal{ class Animal{
class Animal{ void Animal(){System.out.printl
String color="white"; eat(){System.out.println("ea n("animal is created");}
} ting...");} }
class Dog extends } class Dog extends Animal{
Animal{ class Dog extends Animal{ Dog(){
String color="black"; void super();
void printColor(){ eat(){System.out.println("ea System.out.println("dog is
System.out.println(color ting bread...");} created");
);//prints color of Dog void }
class bark(){System.out.println("b }
System.out.println(super arking...");} class TestSuper3{
.color);//prints color void work(){ public static void
of Animal class super.eat(); main(String args[]){
} bark(); Dog d=new Dog();
} } }}
class TestSuper1{ }
public static void class TestSuper2{
main(String args[]){ public static void
Dog d=new Dog(); main(String args[]){
d.printColor(); Dog d=new Dog();
}} d.work();
}}

Final Keyword:
The final keyword is used to restrict the user. The java final keyword can be used
in many context. Final can be:
 variable
 method
 class
If you make any variable as final, you cannot change the value of final variable(It
will be constant).
If you make any method as final, you cannot override it.
If you make any class as final, you cannot extend it.
Polymorphism:
There are two types of polymorphism : compile time polymorphism and runtime
polymorphism. We can perform polymorphism by method overloading and method
overriding.

If you overload static method , it is the example of compile time polymorphism.


Here, we will focus on runtime polymorphism .

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an


overridden method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a
superclass. The determination of the method to be called is based on the object
being referred to by the reference variable.

Abstract :
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.

A class that is declared with abstract keyword, is known as abstract class . It can
have abstract and non-abstract methods (method with body).

it shows only important things to the user and hides the internal details for
example sending sms, you just type the text and send the message. You don't know
the internal processing about the message delivery.

Pure implementation of abstraction is Interface.

abstract class Bank{


abstract int getRateOfInterest();
}

class SBI extends Bank{


int getRateOfInterest(){return 7;}
}
class PNB extends Bank{
int getRateOfInterest(){return 7;}
}

class TestBank{
public static void main(String args[]){
Bank b=new SBI();//if object is PNB, method of PNB will be invoked
int interest=b.getRateOfInterest();
System.out.println("Rate of Interest is: "+interest+" %");
}}
Interface:
An interface is a blueprint of a class. It has static constants and abstract
methods.

There are mainly three reasons to use interface. They are given below.
 It is used to achieve abstraction.
 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling.

interface Printable{
void print();
}

interface Showable{
void show();
}

class A7 implements Printable,Showable{

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


public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}

Abstract class Interface


Abstract class can have abstract and Interface can have only
non-abstract methods. abstract methods. Since Java 8, it can
have default and static methods also.
Abstract class doesn't support multiple Interface supports multiple
inheritance. inheritance.
Abstract class can have final, non- Interface has only static and final
final, static and non-static variables. variables.
Abstract class can provide the Interface can't provide the
implementation of interface. implementation of abstract class.
The abstract keyword is used to declare The interface keyword is used to
abstract class. declare interface.
An abstract class can extend another An interface can extend another Java
Java class and implement multiple Java interface only.
interfaces.
An abstract class can be extended using An interface class can be implemented
keyword extends. using keyword implements.
abstract class can have class members interface are public by default.
like private, protected, etc.
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Encapsulation:
Encapsulation is a process of wrapping code and data together into a single unit.
We can create a fully encapsulated class by making all the data members of the
class private. Now we can use setter and getter methods to set and get the data in
it.

public class Student{


private String name;

public String getName(){


return name;
}
public void setName(String name){
this.name=name
}
}

class Test{
public static void main(String[] args){
Student s=new Student();
s.setName("vijay");
System.out.println(s.getName());
}
}

Das könnte Ihnen auch gefallen