OOPS
OOPS
OOPS
class.
A class creates a new data type that can be used to create objects.
The dot operator links the name of the object with the name of an instance
variable.
Although commonly referred to as the dot operator, the formal
specification for Java categorizes the . as a separator.
The 'new' keyword dynamically allocates(that is, allocates at run
time)memory for an object & returns a reference to it.
This reference is, more or less, the address in memory of the object
allocated by new.
This reference is then stored in the variable.
Thus, in Java, all class objects must be dynamically allocated.
You might be wondering why you do not need to use new for such things as
integers or characters.
The answer is that Java’s primitive types are not implemented as objects.
Rather, they are implemented as “normal” variables.
This is done in the interest of efficiency.
NOTE:
Bus bus = new Bus();
lhs(reference i.e. bus) is looked by compiler & rhs (object i.e. new
Bus()) is looked by jvm
The this Keyword:
Sometimes a method will need to refer to the object that invoked it. To
allow this, Java defines the this keyword.
this can be used inside any method to refer to the current object. That
is, this is always a reference to the object on
which the method was invoked.
final Keyword:
A field can be declared as final. Doing so prevents its contents from
being modified, making it, essentially, a constant.
This means that you must initialize a final field when it is declared.
Constructors:
In the line
Box mybox1 = new Box();
new Box( ) is calling the Box( ) constructor.
// filename: Main.java
class Base {
Base() {
System.out.println("Base Class Constructor Called ");
}
}
Any class will have a default constructor, does not matter if we declare
it in the class or not. If we inherit a class,
then the derived class must call its super class constructor. It is done
by default in derived class.
If it does not have a default constructor in the derived class, the JVM
will invoke its default constructor and call
the super class constructor by default. If we have a parameterised
constructor in the derived class still it calls the
default super class constructor by default. In this case, if the super
class does not have a default constructor,
instead it has a parameterised constructor, then the derived class
constructor should call explicitly call the
parameterised super class constructor.
Understanding static:
A static method can access only static data. It cannot access non-static
data (instance variables)
A non-static member belongs to an instance. It's meaningless without
somehow resolving which instance of a class you
are talking about. In a static context, you don't have an instance, that's
why you can't access a non-static member
without explicitly mentioning an object reference.
In fact, you can access a non-static member in a static context by
specifying the object reference explicitly :
public class Human {
A static method can call only other static methods and cannot call a non-
static method from it.
A static method can be accessed directly by the class name and doesn’t
need any object
A static method cannot refer to "this" or "super" keywords in anyway
As soon as the UseStatic class is loaded, all of the static statements are
run. First, a is set to 3,
then the static block executes, which prints a message and then
initializes b to a*4 or 12. Then main( ) is called,
which calls meth( ), passing 42 to x. The three println( ) statements
refer to the two static variables a and b,
as well as to the local variable x.
NOTE:
public class Static {
class OverloadDemo {
void test(double a){
System.out.println("Inside test(double) a: " + a);
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
int i = 88;
ob.test(i); // this will invoke test(double)
ob.test(123.2); // this will invoke test(double)
}
}
As you can see, this version of OverloadDemo does not define test(int).
Therefore, when test( ) is called with an
integer argument inside Overload, no matching method is found. However,
Java can automatically convert an integer
into a double, and this conversion can be used to resolve the call.
Therefore, after test(int) is not found,
Java elevates i to double and then calls test(double).
Of course, if test(int) had been defined, it would have been called
instead.
Java will employ its automatic type conversions only if no exact match is
found.
Returning Objects:
// Returning an object.
class Test {
int a;
Test(int i) {
a = i;
}
Test incrByTen() {
Test temp = new Test(a+10);
return temp;
}
}
class RetOb {
public static void main(String args[]) {
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
}
}
Output:
ob1.a: 2
ob2.a: 12
Method overriding occurs only when the names and the type signatures of
the two methods are identical.
If they are not, then the two methods are simply overloaded.
Java uses file system directories to store packages. For example, the
.class files for any classes you declare to be
part of MyPackage must be stored in a directory called MyPackage. Remember
that case is significant, and the directory
name must match the package name exactly.
package java.awt.image;
How does the Java run-time system know where to look for packages that you
create? The answer has three parts.
- First, by default, the Java run-time system uses the current working
directory as its starting point.
Thus, if your package is in a subdirectory of the current directory, it
will be found.
- Second, you can specify a directory path or paths by setting the
CLASSPATH environmental variable.
- Third, you can use the -classpath option with java and javac to specify
the path to your classes.
When a package is imported, only those items within the package declared
as public will be available to non-subclasses
in the importing code.
To inherit a class, you simply incorporate the definition of one class
into another by using the extends keyword.
plainbox = weightbox;
(superclass) (subclass)
SUPERCLASS ref = new SUBCLASS(); // HERE ref can only access methods
which are available in SUPERCLASS
Using super:
Whenever a subclass needs to refer to its immediate superclass, it can do
so by use of the keyword super.
super has two general forms. The first calls the superclass’ constructor.
The second is used to access a member of the superclass that has been
hidden by a member of a subclass.
class Box {
private double width;
private double height;
private double depth;
super.member
If you think about it, it makes sense that constructors complete their
execution in order of derivation.
Because a superclass has no knowledge of any subclass, any initialization
it needs to perform is separate from and
possibly prerequisite to any initialization performed by the subclass.
Therefore, it must complete its execution first.
Java’s access modifiers are public, private, and protected. Java also
defines a default access level.
protected applies only when inheritance is involved.
+ : accessible
blank : not accessible
package packageOne;
public class Base
{
protected void display(){
System.out.println("in Base");
}
}
package packageTwo;
public class Derived extends packageOne.Base{
public void show(){
new Base().display(); // this is not working
new Derived().display(); // is working
display();//is working
}
}
protected allows access from subclasses and from other classes in the same
package.
We can use child class to use protected member outside the package but
only child class object can access it.
That's why any Derived class instance can access the protected method in
Base.
The other line creates a Base instance (not a Derived instance!!).
And access to protected methods of that instance is only allowed from
objects of the same package.
display();
-> allowed, because the caller, an instance of Derived has access to
protected members and fields of its subclasses,
even if they're in different packages
new Derived().display();
-> allowed, because you call the method on an instance of Derived and that
instance has access to the protected methods
of its subclasses
new Base().display();
-> not allowed because the caller's (the this instance) class is not
defined in the same package like the Base class,
so this can't access the protected method. And it doesn't matter - as we
see - that the current subclasses a class from
that package. That backdoor is closed ;)
class C
protected member;
// in a different package
class S extends C
Any class that contains one or more abstract methods must also be declared
abstract.
# There can be no objects of an abstract class.
# You cannot declare abstract constructors, or abstract static methods.
# You can declare static methods in abstract class.
Because there can be no objects for abstract class. If they had allowed to
call abstract static methods,
it would that mean we are calling an empty method (abstract) through
classname because it is static.
Any subclass of an abstract class must either implement all of the
abstract methods in the superclass,
or be declared abstract itself.
Abstract classes can include as much implementation as they see fit
i.e.there can be concrete methods(methods with body)
in abstract class.
Type of methods:
Interface can have only abstract methods.
Abstract class can have abstract and non-abstract methods. From Java 8, it
can have default and static methods also.
Final Variables:
Variables declared in a Java interface are by default final.
An abstract class may contain non-final variables.
Type of variables:
Abstract class can have final, non-final, static and non-static variables.
Interface has only static and final variables.
Implementation:
Abstract class can provide the implementation of interface.
Interface can’t provide the implementation of abstract class.
Inheritance vs Abstraction:
A Java interface can be implemented using keyword “implements”
and abstract class can be extended using keyword “extends”.
Multiple implementation:
An interface can extend another Java interface only,
an abstract class can extend another Java class and implement multiple
Java interfaces.
Instead we have java interfaces. they have abstract functions (no body of
functions)
Interfaces specify only what the class is doing, not how it is doing it.
The problem with MULTIPLE INHERITANCE is that two classes may define
different ways of doing the same thing,
and the subclass can't choose which one to pick.
Using interface, you can specify a set of methods that can be implemented
by one or more classes.
Although they are similar to abstract classes, interfaces have an
additional capability:
A class can implement more than one interface. By contrast, a class can
only inherit a single superclass
(abstract or otherwise).
Using the keyword interface, you can fully abstract a class’ interface
from its implementation.
That is, using interface, you can specify what a class must do, but not
how it does it.
By providing the interface keyword, Java allows you to fully utilize the
“one interface, multiple methods”
aspect of polymorphism.
NOTE:
You can declare variables as object references that use an interface
rather than a class type.
This process is similar to using a superclass reference to access a
subclass object.
Any instance of any class that implements the declared interface can be
referred to by such a variable.
When you call a method through one of these references, the correct
version will be called based on the actual instance
of the interface being referred to. Called at run time by the type of
object it refers to.
The method to be executed is looked up dynamically at run time, allowing
classes to be created later than the code which
calls methods on them.
The calling code can dispatch through an interface without having to know
anything about the “callee.”
Nested Interfaces:
For example, you might have a class that implements two interfaces.
If each of these interfaces provides default methods, then some behavior
is inherited from both.
# In all cases, a class implementation takes priority over an interface
default implementation.
# In cases in which a class implements two interfaces that both have the
same default method, but the class does not
override that method, then an error will result.
# In cases in which one interface inherits another, with both defining a
common default method, the inheriting
interface’s version of the method takes precedence.