Beruflich Dokumente
Kultur Dokumente
void barking() {
}
void hungry() {
}
void sleeping() {
}
}
A class can contain any of the following variable types.
• Local variables − Variables defined inside methods, constructors or blocks are called
local variables. The variable will be declared and initialized within the method and the variable
will be destroyed when the method has completed.
• Instance variables − Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance variables can be
accessed from inside any method, constructor or blocks of that particular class.
• Class variables − Class variables are variables declared within a class, outside any
method, with the static keyword.
A class can have any number of methods to access the value of various kinds of methods. In the
above example, barking(), hungry() and sleeping() are methods.
Following are some of the important topics that need to be discussed when looking into classes
of the Java Language.
Constructors
When discussing about classes, one of the most important sub topic would be constructors. Every
class has a constructor. If we do not explicitly write a constructor for a class, the Java compiler
builds a default constructor for that class.
Each time a new object is created, at least one constructor will be invoked. The main rule of
constructors is that they should have the same name as the class. A class can have more than one
constructor.
Following is an example of a constructor −
Example
public class Puppy {
public Puppy() {
}
void display()
{
/* print maxSpeed of base class (vehicle) */
System.out.println("Maximum Speed: " + super.maxSpeed);
}
}
/* Subclass Student */
class Student extends Person
{
void message()
{
System.out.println("This is student class");
}
/* superclass Person */
class Person
{
Person()
{
System.out.println("Person class Constructor");
}
}
}
this keyword in java
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();
}}
Java Objects:
When class is defined, only the specification for the object is defined; no memory or storage is
allocated.
class Lamp {
boolean isOn;
void turnOn() {
isOn = true;
}
void turnOff() {
isOn = false;
}
void displayLightStatus() {
System.out.println("Light on? " + isOn);
} }
class ClassObjectsExample {
public static void main(String[] args) {
Lamp l1 = new Lamp(), l2 = new Lamp();
l1.turnOn();
l2.turnOff();
l1.displayLightStatus();
l2.displayLightStatus();
} }
When you run the program, the output will be:
Super Class: The class whose features are inherited is known as super class(or a base class or a
parent class).
Sub Class: The class that inherits the other class is known as sub class(or a derived class,
extended class, or child class). The subclass can add its own fields and methods in addition to the
superclass fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new
class and there is already a class that includes some of the code that we want, we can derive our
new class from the existing class. By doing this, we are reusing the fields and methods of the
existing class.
Single Inheritance : In single inheritance, subclasses inherit the features of one superclass. In
image below, the class A serves as a base class for the derived class B.
Single_Inheritance
//Java program to illustrate the
// concept of single inheritance
import java.util.*;
import java.lang.*;
import java.io.*;
class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}
Geeks
for
Geeks
Multilevel Inheritance : In Multilevel Inheritance, a derived class will be inheriting a base class
and as well as the derived class also act as the base class to other class. In below image, the class
A serves as a base class for the derived class B, which in turn serves as a base class for the
derived class C. In Java, a class cannot directly access the grandparent’s members.
Multilevel_Inheritance
class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}
// Drived class
public class Main
{
public static void main(String[] args)
{
three g = new three();
g.print_geek();
g.print_for();
g.print_geek();
}
}
Output:
Geeks
for
Geeks
Hierarchical Inheritance : In Hierarchical Inheritance, one class serves as a superclass (base
class) for more than one sub class.In below image, the class A serves as a base class for the
derived class B,C and D.
hie
// Java program to illustrate the
// concept of Hierarchical inheritance
import java.util.*;
import java.lang.*;
import java.io.*;
class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}
// Drived class
public class Main
{
public static void main(String[] args)
{
three g = new three();
g.print_geek();
two t = new two();
t.print_for();
g.print_geek();
}
}
Output:
Geeks
for
Geeks
Multiple Inheritance (Through Interfaces) : In Multiple inheritance ,one class can have more than
one superclass and inherit features from all parent classes. Please note that Java does not support
multiple inheritance with classes. In java, we can achieve multiple inheritance only through
Interfaces. In image below, Class C is derived from interface A and B.
Multiple_Inheritance
// Java program to illustrate the
// concept of Multiple inheritance
import java.util.*;
import java.lang.*;
import java.io.*;
interface one
{
public void print_geek();
}
interface two
{
public void print_for();
}
// Drived class
public class Main
{
public static void main(String[] args)
{
child c = new child();
c.print_geek();
c.print_for();
c.print_geek();
}
}
Output:
Geeks
for
Geeks
Hybrid Inheritance(Through Interfaces) : It is a mix of two or more of the above types of
inheritance. Since java doesn’t support multiple inheritance with classes, the hybrid inheritance
is also not possible with classes. In java, we can achieve hybrid inheritance only through
Interfaces.
hybrid
Important facts about inheritance in Java
Default superclass: Except Object class, which has no superclass, every class has one and only
one direct superclass (single inheritance). In the absence of any other explicit superclass, every
class is implicitly a subclass of Object class.
Superclass can only be one: A superclass can have any number of subclasses. But a subclass
can have only one superclass. This is because Java does not support multiple inheritance with
classes. Although with interfaces, multiple inheritance is supported by java.
Inheriting Constructors: A subclass inherits all the members (fields, methods, and nested
classes) from its superclass. Constructors are not members, so they are not inherited by
subclasses, but the constructor of the superclass can be invoked from the subclass.
Private member inheritance: A subclass does not inherit the private members of its parent
class. However, if the superclass has public or protected methods(like getters and setters) for
accessing its private fields, these can also be used by the subclass.
Polymorphism in Java
Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many
and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.
If you overload a static method in Java, it is the example of compile time polymorphism. Here,
we will focus on runtime polymorphism in java.
Runtime Polymorphism in Java
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.
Abstraction in Java
Abstraction is a methodology of hiding the implementation of internal details and showing the
functionality to the users.
In Java, abstraction is achieved using Abstract classes and interfaces.
//abstract method
public abstract void work();
@Override
public String toString(){
return "Name="+this.name+"::Gender="+this.gender;
}
@Override
public void work() {
if(empId == 0){
System.out.println("Not working");
}else{
System.out.println("Working as employee!!");
}
}
Interface
import java.io.*;
// A simple interface
interface in1
{
// public, static and final
final int a = 10;
// public and abstract
void display();
}
// A class that implements an interface.
class testClass implements in1
{
// Implementing the capabilities of interface.
public void display()
{
System.out.println("Geek");
}
// Driver Code
public static void main (String[] args)
{
testClass t = new testClass();
t.display();
System.out.println(a);
}
}
Array
class Test
{
// Driver method
public static void main(String args[])
{
int arr[] = {3, 1, 2, 5, 4};
Upcasting in Java –
Upcasting is casting a subtype to a supertype, upward to the inheritance tree. Upcasting happens
automatically and we don’t have to explicitly do anything. Let us see a program snippet –
// Base Class
class Parent
{
void show() { System.out.println("Parent's show()"); }
}
// Inherited class
class Child extends Parent
{
// This method overrides show() of Parent
@Override
void show() { System.out.println("Child's show()"); }
}
class Main
{
public static void main(String[] args)
{
Parent obj1 = new Child();
obj1.show();
}
}
Output
Child’s show()
downcasting
class Animal { }