Java基础知识

之前在面Tripadvisor的时候面了很简单的一道java基础知识,结果没答出来,决定做一些小总结,经常更新更新自己复习看看。


1. String方面

String s = "abc";

String s = new String("abc");

这两个有什么区别


在java中,用heap和stack存储  The heap stores all objects including arrays, and all class variables

The stack stores all local variables and primitive types.

Primitive types有8个:

byte: 8-bit integer -128 - 127

short: 16-bit integer  -32768-32767

int: 32-bit integer      -2147483648 - 2147483647

long: 64-bit integer

double: 64-bit floating point number

float: 32-bit

boolean: true/false

char: a character


所以第一个会在stack中创建三个char type: ‘a’, ‘b’, ‘c’,然后在String pool中创建一个String "abc"

第二个除了以上两个步骤,还需要在heap中创建String对象。

这个String pool的用处在于,如果下一次创建新的String对象,比如String x = "abc"; 它会先在字符串池里搜索有没有这个String, 有的话直接引用就可以了。


《String的特性》

1、String类是final的,不可被继承。
2、String类是的本质是字符数组char[], 并且其值不可改变。
3、String类对象有个特殊的创建的方式,就是直接指定比如String x = "abc","abc"就表示一个字符串对象。而x是"abc"对象的地址,也叫做"abc"对象的引用。
4、String对象可以通过“+”串联。串联后会生成新的字符串。
5、Java运行时会维护一个String Pool(String池),JavaDoc翻译很模糊“字符串缓冲区”。String池用来存放运行时中产生的各种字符串,并且池中的字符串的内容不重复。而一般对象不存在这个缓冲池,并且创建的对象仅仅存在于方法的堆栈区。

 6、创建字符串的方式很多,归纳起来有三类:
其一,使用new关键字创建字符串,比如String s1 = new String("abc");
其二,直接指定。比如String s2 = "abc";
其三,使用串联生成新的字符串。比如String s3 = "ab" + "c"; 


 object typesprimitive types
contains areferencevalue
how definedclass definitionbuilt in java
hwo created"new""6", "3.4", "true"
how initializedconstructordefault value
how usedmethodsoperations("+")



2. Java I/O classes

Objects in System class for interacting with a user:

System.out is a PrntStream object that outputs to the screen.

System.in is an InputStream object that reads from the keyboard.


readLine method is defined on BufferedReader objects.

- How do we construct a BufferedReader? With an InputStream reader.

- How do we construct an InputStreamReader? With an InputStream.

- How do we construct an InputStream? System.in is one.

InputStream reads raw data.

InputStreamReader composes it into characters.(typically 2 bytes)

BufferedReader composes chars into entire lines of text.


BufferedReader keybd = new BufferedReader(new InputStreamReader(System.in));

System.out.println(keybd.readLine());


3. JVM

 What is JVM ? Why is Javacalled the “Platform Independent Programming Language” ? A Java virtual machine (JVM) is aprocess virtual machine that can execute Java bytecode. Each Java source file is compiled into a bytecode file,which is executed by the JVM. Java was designed to allow application programsto be built that could be run on any platform, without having to be rewrittenor recompiled by the programmer for each separate platform. A Java virtualmachine makes this possible, because it is aware of the specific instructionlengths and other particularities of the underlying hardware platform.

Every Java program is first compiled into an intermediate language called Java bytecode. The JVM is used primarily for 2 things: the first is to translate the bytecode into the machine language for a particular computer, and the second thing is to actually execute the corresponding machine-language instructions as well. The JVM and bytecode combined give Java its status as a "portable" language – this is because Java bytecode can be transferred from one machine to another.

Type a source code ---> Save as .java ---> compiler compiles source code into.class file, which is made up of bytecodes. ---> JVM runs .class file.


4. Object-Oriented

Java is a computer programming language that is concurrent, class-based and object-oriented. The advantages of object oriented software development are shown below:

  • Modular development of code, which leads to easy maintenance and modification.
  • Reusability of code.
  • Improved reliability and flexibility of code.
  • Increased understanding of code.
Object-oriented programming contains many significant features, such as encapsulationinheritancepolymorphism and abstraction. We analyze each feature separately in the following sections.

Encapsulation

Encapsulation provides objects with the ability to hide their internal characteristics and behavior. Each object provides a number of methods, which can be accessed by other objects and change its internal data. In Java, there are three access modifiers: public, private and protected. Each modifier imposes different access rights to other classes, either in the same or in external packages. Some of the advantages of using encapsulation are listed below:

  • The internal state of every objected is protected by hiding its attributes.
  • It increases usability and maintenance of code, because the behavior of an object can be independently changed or extended.
  • It improves modularity by preventing objects to interact with each other, in an undesired way.

Polymorphism 

is the capability to provide multiple implementations of an action and to select the correct implementation based on the surrounding context. For example, a class might define two versions of a method with different parameters. Or the same method might be defined both in a parent class and a subclass, the latter overriding the former for instances of the subclass.

Inheritance

Inheritance provides an object with the ability to acquire the fields and methods of another class, called base class. Inheritance provides re-usability of code and can be used to add additional features to an existing class, without modifying it.

Abstraction

Abstraction is the process of separating ideas from specific instances and thus, develop classes in terms of their own functionality, instead of their implementation details. Java supports the creation and existence of abstract classes that expose interfaces, without including the actual implementation of all methods. The abstraction technique aims to separate the implementation details of a class from its behavior.

5. public, protected, private

public is visible to everywhere.
protected field/method is visible to declaring class & all its subclasses.(between public and private)
private不能被该class以外的class用 private aren't visible to subclasses.

declarationin the same packagein a subclasseverywhere
public                yes           yes          yes 
protected                yes           yes 
package                yes  
private   

6. Object versus Class

So, we can say that whereas a class is a general concept (like an Animal), an object is a very specific embodiment of that class, with a limited lifespan (like a lion, cat, or a zebra). Another way of thinking about the difference between a class and an object is that a class provides a template for something more specific that the programmer has to define, which he/she will do when creating an object of that class.

7. abstract class and interface

A subclass can modify a superclass in 3 ways:
1. It can declare new fields.
2. It can declare new methods.
3. It can override old methods with new implementations.

An abstract class is a class whose sole purpose is to be extended. A method is declared abstract when it has a method heading, but no body – which means that an abstract method has no implementation code inside curly braces like normal methods do. 

An abstract class may provide some methods with definitions – so an abstract class can have non-abstract methods with actual implementation details. An abstract class can also have constructors and instance variables as well. An interface, however, can not provide any method definitions – it can only provide method headings. Any class that implements the interface is responsible for providing the method definition/implementation.

Java interfaces
= public method prototype & behaviors

difference:

  • All methods in an interface are implicitly abstract. On the other hand, an abstract class may contain both abstract and non-abstract methods.
  • A class may implement a number of Interfaces, but can extend only one abstract class.
  • In order for a class to implement an interface, it must implement all its declared methods. However, a class may not implement all declared methods of an abstract class. Though, in this case, the sub-class must also be declared as abstract.
  • Abstract classes can implement interfaces without even providing the implementation of interface methods.
  • Variables declared in a Java interface is by default final. An abstract class may contain non-final variables.
  • Members of a Java interface are public by default. A member of an abstract class can either be private, protected or public.
  • An interface is absolutely abstract and cannot be instantiated. An abstract class also cannot be instantiated, but can be invoked if it contains a main method.

    1.相同点
      A. 两者都是抽象类,都不能实例化。
      B. interface实现类及abstract class的子类都必须要实现已经声明的抽象方法。

    2. 不同点
      A. interface需要实现,要用implements,而abstract class需要继承,要用extends。
      B. 一个类可以实现多个interface,但一个类只能继承一个abstract class。
      C. interface强调特定功能的实现,而abstract class强调所属关系。 
     D. 尽管interface实现类及abstract class的子类都必须要实现相应的抽象方法,但实现的形式不同。interface中的每一个方法都是抽象方法,都只是声明的 (declaration, 没有方法体),实现类必须要实现。而abstract class的子类可以有选择地实现。
      这个选择有两点含义:
        一是Abastract class中并非所有的方法都是抽象的,只有那些冠有abstract的方法才是抽象的,子类必须实现。那些没有abstract的方法,在Abstrct class中必须定义方法体。
        二是abstract class的子类在继承它时,对非抽象方法既可以直接继承,也可以覆盖;而对抽象方法,可以选择实现,也可以通过再次声明其方法为抽象的方式,无需实现,留给其子类来实现,但此类必须也声明为抽象类。既是抽象类,当然也不能实例化。
      E. abstract class是interface与class的中介。
      interface是完全抽象的,只能声明方法,而且只能声明public的方法,不能声明private及protected的方法,不能定义方法体,也 不能声明实例变量。然而,interface却可以声明常量变量,并且在JDK中不难找出这种例子。但将常量变量放在interface中违背了其作为接 口的作用而存在的宗旨,也混淆了interface与类的不同价值。如果的确需要,可以将其放在相应的abstract class或Class中。
      abstract class在interface及Class中起到了承上启下的作用。一方面,abstract class是抽象的,可以声明抽象方法,以规范子类必须实现的功能;另一方面,它又可以定义缺省的方法体,供子类直接使用或覆盖。另外,它还可以定义自己 的实例变量,以供子类通过继承来使用。


8. static method, static field
- a local variable is gone when methods end.
- an instance variable(non-static field) lasts as long as an object exists.
- A class variable(static field) lasts as long as the program.

static field:
A single variable shared by a whole class of objects.
Also called class variables.
Instance variables are variables that every object has its own unique variable.

static method:
Static method doesn't implicitly take an object as a parameter.
Public static void print Human(){
System.out.print(numberOfHuman);
}
In a static method, there is no "this".



9. pass by value, pass by reference
When an object is passed by value, this means that a copy of the object is passed. Thus, even if changes are made to that object, it doesn’t affect the original value. When an object is passed by reference, this means that the actual object is not passed, rather a reference of the object is passed. Thus, any changes made by the external method, are also reflected in all places.
举个例子:
public void swap(int a, int b){
int temp = a;
a = b;
b = temp;
}
int x = 1;
int y = 2;
swap(x, y);
得到的结果还是1和2,原因是这里的swap里的a和b复制了x和y的value,然后改变了a和b的值,而x和y的值并没有改变。
x ---> 1       ----->      x ---> 1         ----->      x ---> 1
y ---> 2                    y ---> 2                      y ---> 2
                               a ---> 1                     a ---> 2
                               b ---> 2                     b ---> 1


public void makeCircle(Circle circle, int x, int y){
circle.setX(x);
circle.setY(y);
circle = new Circle();
}
Circle myC = new Circle();
makeCircle(myC, 1, 2);

这表示一开始myC是一个新的circle,然后通过makeCircle以后,我其实在复制了一个叫circle的来指向同一个object, 所以改变circle就等于改变了myC, 然后我给circle赋值了新的object,而并不影响myC,只是让circle变成了一个新的object.


10. final
根据程序上下文环境,Java关键字final有“这是无法改变的”或者“终态的”含义,它可以修饰非抽象类、非抽象类成员方法和变量。你可能出于两种理解而需要阻止改变:设计或效率。
        final类不能被继承,没有子类,final类中的方法默认是final的。
        final方法不能被子类的方法覆盖,但可以被继承。
        final成员变量表示常量,只能被赋值一次,赋值后值不再改变。
        final不能用于修饰构造方法。
        注意:父类的private成员方法是不能被子类方法覆盖的,因此private类型的方法默认是final类型的。

这里有个例子,比如有一个class叫Apple

final Apple a = new Apple(3);
a.setSize(5); 这就没问题,因为a其实是一个reference,它point to 一个apple object, 然后这个object里我们改变它的尺寸。
如果是 a = new Apple(5); 这就是错的,因为这个时候我们改变了a这个引用,让a指向了一个新的apple object,而final是不允许reassign的。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值